gpt4 book ai didi

javascript - 重置原型(prototype)对象的构造函数属性

转载 作者:行者123 更新时间:2023-11-30 17:43:10 24 4
gpt4 key购买 nike

考虑以下片段:

function shape(){
this.name = "2d shape"
}

function triangle(){
this.name = "triangle";
this.ttest = function(){
alert("in triangle constructor");
}
}

function equitriangle(){
this.name = "equitriangle"
}

var s = new shape();
triangle.prototype = s;
equitriangle.prototype = new triangle();

var et = new equitriangle();

alert(et.name); // this alerts equitriangle
et.ttest(); // this alerts in triangle constructor
alert(x.isPrototypeOf(et));// this alerts true
alert(et.constructor); // **but this alerts the shape constructor instead of the equitriangle constructor**

问题 1)为什么我得到形状构造函数?

但是如果我在之前添加以下行

equitriangle.prototype.constructor = equitriangle;
var et = new equitriangle();
....
.....
.....
alert(et.constructor); // this now alerts the equitriangle constructor which should be the expected output.

我读到过,当原型(prototype)对象像本例中那样被覆盖时,可能会导致意想不到的结果,“重置”构造函数是一种很好的做法

equitriangle.prototype.constructor = equitriangle;

但是上面这行对我来说没有意义。

问题 2) 上面这行有什么意义?

最佳答案

Why do i get the shape constructor?

注意et.constructor是原型(prototype)继承的属性:

et.constructor; // shape
et.hasOwnProperty('constructor'); // false

然后,.constructor继承自equitriangle.prototype

但还要注意 equitriangle.prototype.constructor 继承自 triangle.prototype

但还要注意 triangle.prototype.constructor 继承自 shape.prototype

最后,shape.prototype.hasOwnProperty('constructor')true

关于javascript - 重置原型(prototype)对象的构造函数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com