gpt4 book ai didi

javascript - 为什么不调用原型(prototype)中声明的函数?

转载 作者:数据小太阳 更新时间:2023-10-29 04:09:18 26 4
gpt4 key购买 nike

var p = function () {
this.show = function () {
alert('hello world!!!');
}
}

p.prototype.show = function() {
alert('haha');
}

var o = new p();
o.show();

它提醒 “hello world!!!”,为什么?

我可以修改原型(prototype)方法吗,如果可以怎么修改?

最佳答案

那是因为您在构造函数中定义的特定函数覆盖了通过原型(prototype)继承的函数。

来自 EcmaScript specification :

Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. When a reference is made to a property in an object, that reference is to the property of that name in the first object in the prototype chain that contains a property of that name. In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

简而言之:在查找函数(或任何属性的名称)时,您从对象开始,然后在原型(prototype)链中向上移动。

关于javascript - 为什么不调用原型(prototype)中声明的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718890/

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