调用函数调用()和调用继承类的隐式构造函数有什么区别?
例1:
function DepthRectangle(w, h, d){
Rectangle.call(this, w, h);
this.depth = d;
}
例2:
function DepthRectangle(w, h, d){
this = new Rectangle(w, h);
this.depth = d;
}
Rectangle的构造函数:
function Rectangle(w, h){
this.width = w;
this.height = h;
}
答案 0 :(得分:3)
好吧,你的第二个例子不起作用,因为this
值不可分配,它不是分配的有效左侧表达式。
但是,假设你有:
function DepthRectangle(w, h, d){
var obj = new Rectangle(w, h);
obj.depth = d;
return obj;
}
在这种情况下,不同之处在于此函数返回的对象将直接从Rectangle.prototype
继承,而不是从DepthRectangle
继承。
例如,使用上述功能:
//...
DepthRectangle.prototype.inherited = "foo";
Rectangle.prototype.inherited = "bar";
var obj = new DepthRectangle(1,2,3); // note: new is not really needed
obj.inherited; // "bar", from Rectangle.prototype
obj instanceof DepthRectangle; // false
在第一个示例中,使用call
方法只执行Rectangle
函数,但this
值指向DepthRectangle
上创建的对象,这意味着该对象实际上仍然继承自DepthRectangle.prototype
。
答案 1 :(得分:2)
嗯,首先,分配this = new Rectangle(w, h)
可能会抛出
Uncaught ReferenceError: Invalid left-hand side in assignment
.call()
基本上可以让你做同样的事情。它的工作原理是允许您在要调用的函数中设置this
的值。如果您正在调用另一个函数构造函数,它将应用于您的构造函数到当前的this
对象。
请注意,Rectangle
的原型不会以这种方式复制,如果你想要它,你需要考虑到它。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/call
答案 2 :(得分:2)
调用函数调用()和调用继承类的隐式构造函数有什么区别?
JavaScript中没有隐式构造函数。
代码
Rectangle.call(this, w, h);
...将确保在Rectangle
内,this
引用this
在调用代码中引用的对象。
在代码中
new Rectangle(w, h);
this
中的 ... Rectangle
将引用由new
运算符创建的新对象。
Re Example 2:
this = new Rectangle(w, h);
您无法分配到this
。 this
由函数的调用方式设置,在函数处理过程中无法更改。
具体来说,
Rectangle.call(this, w, h);
在创建层次结构时使用了idiom,以确保使用Rectangle
事物初始化新创建的对象,可能是因为当前构造函数(在您的情况下为DepthRectangle
)想要重用该功能