[英]How does an object reference itself in Javascript?
我正在尝试用javascript继承,并编写了这两个函数:
Object.prototype.inherits=function(obj){this.prototype=new obj;}
Object.prototype.pass=function(obj){obj.prototype=new this;}
这段代码效果很好:
Dog.inherits(Animal);
但是以下失败:
Animal.pass(Dog);
据我了解,我的传递函数不起作用,因为“ this”不是对对象实例本身的引用吗? 如果是这样,我如何从自身内部引用该对象?
提前致谢!
好吧,实际上两者的作用完全相同:
Dog.prototype = new Animal;
在以下情况下,方法内的this
值将引用调用引用的基础对象 :
Dog.inherits(Animal);
this
值将引用Dog
构造函数,而obj
参数将是Animal
函数。
你打电话时:
Animal.pass(Dog);
this
值将引用Animal
函数,最后做的事情与inherits
方法完全相同,但是反之。
我建议您不要扩展Object.prototype
对象,因为它可能会引起很多问题,例如,这两个属性将在任何for-in
循环中枚举,例如:
for (var prop in {}) { // <-- an empty object!
alert(prop); // will alert 'inherits' and 'pass'
}
所有对象都继承自Object.prototype
,并且似乎只打算在Function对象上使用这些方法,扩展Function.prototype
对象或将这些方法实现为带有两个参数的Function.prototype
会更安全。
对我有用,测试代码如下:
function Animal() {}
Animal.prototype.isanimal= 1;
function Dog() {}
Animal.pass(Dog);
Dog.prototype.isdog= 2;
alert(new Dog().isanimal); // 1
alert(new Dog().isdog); // 2
但是,请记住, new this
或new obj
将调用函数this/obj
,创建一个新的完整实例。 如果该函数中的构造函数代码希望接收一些自变量或设置实例状态,则可能会遇到问题。 要创建新的this
而不将this
作为函数调用,可以使用不执行任何操作的其他构造函数:
function nonconstructor() {}
nonconstructor.prototype= this.prototype;
obj.prototype= new nonconstructor();
另外,您应该避免在Object
原型制作。 这将给使用Object
作为通用查找图的代码带来麻烦。 由于您似乎只使用构造函数,因此在Function
原型制作应能满足您的需求,并且更加安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.