简体   繁体   English

链接原型和原型继承

[英]Chaining prototypes and prototype inheritance

function Person(name){
    this.name=name
}
var julia=new Person("Julia");

Person.prototype.sayName=function(){
return "Hello, dear "+ this.name;
}

function Other(name){
this.name=name;
}

var mike=new Other("Mike");

Other.prototype=Object.create(Person.prototype);
mike.sayName();

When I call mike.sayName(); 当我打电话给mike.sayName(); it doesn't work and I get mike.sayName is not a function. 它不起作用,我得到了mike.sayName不是一个函数。 I dont understand why? 我不明白为什么? By using Object.create I let Other.prototype inherit from the Person prototype which had the method sayName. 通过使用Object.create,我让Other.prototype继承自具有方法sayName的Person原型。 Now, why am I not being able to run mike.sayName(); 现在,为什么我不能运行mike.sayName();?

Thanks!!! 谢谢!!!

The prototype property of a constructor is only special because it's used as the [[Prototype]] value when creating instances. 构造函数的prototype属性仅是特殊的,因为在创建实例时将其用作[[Prototype]]值。 However, replacing prototype with another object will only affect instances created after the change, it won't magically update the [[Prototype]] of existing instances. 但是,用另一个对象替换prototype只会影响更改后创建的实例,不会神奇地更新现有实例的[[Prototype]]。

var oldproto = Other.prototype;
var mike = new Other("Mike");
Object.getPrototypeOf(mike); // oldproto
Other.prototype = Object.create(Person.prototype);
Object.getPrototypeOf(mike); // oldproto

So just swap the order: 因此,只需交换订单:

Other.prototype = Object.create(Person.prototype);
var mike = new Other("Mike");

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

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