设置“构造函数”的优点在于, “原型”中的属性 [英] Advantages of setting the "constructor" Property in the "prototype"
本文介绍了设置“构造函数”的优点在于, “原型”中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript原型继承中,添加prototype.constructor属性的目的是什么。让我以一个例子解释。
In JavaScript Prototype inheritance, what is the goal of adding prototype.constructor property. Let me explain with an example.
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。
The following lines return always true in all case, when adding Sub.prototype.constructor = Sub or not.
console.log(inst instanceof Sub) // true
console.log(inst instanceof Super) // true
我想,当获取新实例时,或者当和/或如何时,它可能会有用?
I guess, it may be useful when getting new instances but when and/or how?
。
推荐答案
只需正确地重置构造函数
属性,用于构造对象的函数。
It's just to properly reset the constructor
property to accurately reflect the function used to construct the object.
Sub.prototype = new Super();
console.log(new Sub().constructor == Sub);
// -> 'false'
Sub.prototype.constructor = Sub;
console.log(new Sub().constructor == Sub);
// -> 'true'
这篇关于设置“构造函数”的优点在于, “原型”中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文