在 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
我想,它在获取新实例时可能很有用,但何时和/或如何?
提前致谢。
最佳答案
只是适本地重新设置constructor
属性,以准确反射(reflect)用于构造对象的函数。
Sub.prototype = new Super();
console.log(new Sub().constructor == Sub);
// -> 'false'
Sub.prototype.constructor = Sub;
console.log(new Sub().constructor == Sub);
// -> 'true'
关于javascript - 在 "constructor"中设置 "prototype"属性的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4944278/