设置“构造函数"的优点“原型"中的属性 [英] Advantages of setting the "constructor" Property in the "prototype"

查看:25
本文介绍了设置“构造函数"的优点“原型"中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript Prototype 继承中,添加prototype.constructor 属性的目的是什么.让我用一个例子来解释.

<前>var Super = function() {this.superProperty = '超级属性'}var Sub = function() {this.subProperty = '子属性'}Sub.prototype = new Super();Sub.prototype.constructor = Sub;//语句的优点var inst = new Sub();

以下几行在所有情况下都返回 true,无论是否添加 Sub.prototype.constructor = Sub.

<前>console.log(inst instanceof Sub)//真console.log(inst instanceof Super)//真

我想,它在获取新实例时可能有用,但何时和/或如何?

提前致谢.

解决方案

只是适当地重置constructor属性,以准确反映用于构造对象的函数.

Sub.prototype = new Super();console.log(new Sub().constructor == Sub);//->'错误的'Sub.prototype.constructor = Sub;console.log(new Sub().constructor == Sub);//->'真的'

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();

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?

Thanks in advance.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆