Fat*_*cet 16 javascript inheritance constructor prototype
在JavaScript Prototype继承中,添加prototype.constructor属性的目标是什么.让我举个例子来解释一下.
var Super = function() {
this.superProperty = 'Super Property'
}
var Sub = function() {
this.subProperty = 'Sub Property'
}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub; // advantages of the statement
var inst = new Sub();
在添加Sub.prototype.constructor = Sub时,以下行在所有情况下都返回true.
console.log(inst instanceof Sub) // true console.log(inst instanceof Super) // true
我猜,它在获取新实例时可能会有用但是何时和/或如何?
提前致谢.
And*_*y E 10
只是正确地重置constructor属性以准确反映用于构造对象的函数.
Sub.prototype = new Super();
console.log(new Sub().constructor == Sub);
// -> 'false'
Sub.prototype.constructor = Sub;
console.log(new Sub().constructor == Sub);
// -> 'true'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2413 次 |
| 最近记录: |