简体   繁体   English

为什么在原型中声明的函数没有被调用?

[英]Why isn't the function declared in the prototype called?

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

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

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

It alerts "hello world!!!" 它警告"hello world!!!" , why? ,为什么?

Can I modify prototype method, if yes how? 我可以修改原型方法,如果是的话怎么样?

That's because the specific function you define in the constructor overrides the one that is inherited through the prototype. 那是因为您在构造函数中定义的特定函数会覆盖通过原型继承的函数。

From EcmaScript specification : 来自EcmaScript规范

Every object created by a constructor has an implicit reference (called the object's prototype) to the value of its constructor's “prototype” property. 构造函数创建的每个对象都有一个隐式引用(称为对象的原型)到其构造函数的“prototype”属性的值。 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. 等等。

In short : when looking for a function (or any property by its name), you start at the object and then go up in the prototype chain. 简而言之:在查找函数(或其名称的任何属性)时,从对象开始,然后进入原型链。

您在p函数中覆盖prototype.show方法。

In Javascript when a property is resolved the engine first looks at the properties of an object. 在Javascript中解析属性时,引擎首先查看对象的属性。 In your example the object would be represented by this . 在您的示例对象将被表示为this If it finds the property, in this case show (Remember functions can be properties) it uses that property. 如果找到属性,在本例中show (记住函数可以是属性),它将使用该属性。 If the property is not found it then iterates down the prototype chain in an effort to resolve the property. 如果找不到该属性,则迭代原型链以努力解析该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM