7

我正在阅读javascript 中的 mixin 模式,但遇到了这段我不明白的代码:

SuperHero.prototype = Object.create( Person.prototype );

原始代码中实际上有一个错字(大写的 H)。如果我小写它,它会起作用。但是,如果我真的删除了该行,一切似乎都一样。

这是完整的代码:

var Person =  function( firstName , lastName ){
  this.firstName = firstName;
  this.lastName =  lastName;
  this.gender = "male";
};

// a new instance of Person can then easily be created as follows:
var clark = new Person( "Clark" , "Kent" );

// Define a subclass constructor for for "Superhero":
var Superhero = function( firstName, lastName , powers ){

    // Invoke the superclass constructor on the new object
    // then use .call() to invoke the constructor as a method of
    // the object to be initialized.

    Person.call( this, firstName, lastName );

    // Finally, store their powers, a new array of traits not found in a normal "Person"
    this.powers = powers;
};

SuperHero.prototype = Object.create( Person.prototype );
var superman = new Superhero( "Clark" ,"Kent" , ["flight","heat-vision"] );
console.log( superman ); 

// Outputs Person attributes as well as powers

做什么SuperHero.prototype = Object.create( Person.prototype );

4

3 回答 3

4

Person它创建一个从构造函数的原型对象继承的新对象。

就像你这样做一样。

SuperHero.prototype = new Person();

除了它在Person没有实际调用Person构造函数中的代码的情况下创建实例。

这个对象被用作SuperHero构造函数的原型对象,这样当你创建一个SuperHero实例时,它会继承所有的原型属性Person,以及任何直接添加到SuperHero原型对象的原型属性。

于 2012-09-11T17:58:53.330 回答
1

它完全按照文档所述:

使用指定的原型对象和属性创建一个新对象。

proto这种情况下是Person

参数说明如下:

应该是新创建对象的原型的对象。

您的代码Object.create( Person.prototype );返回一个对象,该对象复制一个人的属性(在本例中为名字、姓氏和性别)并将它们分配给 SuperHero。

Person请注意 a和 a之间的相似之处,SuperHero它们都包含 afirstName和 a lastName。还要注意区别,Person包含一个gender属性,而你的SuperHero包含一个powers属性。

于 2012-09-11T17:58:22.000 回答
1
SuperHero.prototype = Object.create( Person.prototype );

这基本上是让SuperHero继承所有的属性/原型Person。它与 using 几乎相同new,但采用了新的 ECMAScript 5 *Object.create()` 方式。如果它有助于理解它,也可以这样写。

SuperHero.prototype = new Person();

我不喜欢专门链接原型,因为这意味着两个原型是交织在一起的,我更喜欢一个是子类,一个是超类。

自己查看它们的一个好方法是做这样的事情。在这里,您可以真正看到SuperHeroPerson. 请注意,它具有所有属性(第一个/最后一个/等),并且是附加的权力。

jsFiddle 演示

var person = new Person();
SuperHero.prototype = person; // inheritance here
// the Object.create way is ECMAScript 5 (which not all browsers support yet sadly)

var superman = new SuperHero( "Clark" ,"Kent" , ["flight","heat-vision"] );
console.log( person );
console.log( superman ); ​
于 2012-09-11T18:03:28.557 回答