首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

javascript中new的模拟兑现

2012-11-23 
javascript中new的模拟实现/*通过下面的代码,可以在FF和Chrome下模拟new的实现*///work as a constructor

javascript中new的模拟实现

/*通过下面的代码,可以在FF和Chrome下模拟new的实现*///work as a constructor to create an objectfunction constructorFn(name) {   this.name = name;}//add a method to its prototype. NOTE: just a function has a prototype propertyconstructorFn.prototype.callA = function(){   alert('I am callA');};//add a property to itss prototypeconstructorFn.prototype.propertyB = "I am property B";function ObjectFactory() {   //获取第一个参数,本质是一个function,将作为一个构造函数, 类似arguments.shift(), arguments是Array-Like对象,shift移除数组中的第一个元素并返回该元素。   //问题:这里为啥不能直接调用arguments.shift()呢?   var constructor = Array.prototype.shift.call(arguments);       /*   在FF或者Chrome等支持__proto__属性的浏览器,可以先改变对应的原型链后进行调用。   arguments.__proto__ = Array.prototype;   var constructor     = arguments.shift();   */      //new 的第一步是生成一个对象   var obj = {};    //new的第二步是改变对象原来的原型链,使之等于对应构造函数的prototype,因此构造函数的prototype的所有属性和方法均可以在新生成的对象中使用   obj.__proto__ =  (typeof constructor.prototype === 'number')? Object.prototype : constructor.prototype;      //new的第三步是调用对应的构造函数,并把对象作为构造函数的this指针传入。   var ret = constructor.apply(obj, arguments); //此时的arguments已经移除了第一个元素了,即是后面的参数部分,本质是调用了构造函数   return (typeof ret === 'object' )? ret : obj;};//用模拟new构造的对象var a = ObjectFactory(constructorFn, 'tenfyguo' );alert (a.name);  a.callA();alert(a.propertyB);//用传统new构造的对象var b = new constructorFn('hello');alert(b.name);b.callA();alert(b.propertyB);


热点排行