Object.create(Class.prototype)在这段代码中做了什么?

时间:2012-09-11 17:50:30

标签: javascript

我正在阅读有关mixin pattern in javascript的内容,我遇到了一段我不明白的代码:

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 );做了什么?

3 个答案:

答案 0 :(得分:4)

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

就像你这样做一样。

SuperHero.prototype = new Person();

除了创建Person实例而不实际调用Person构造函数中的代码。

此对象用作SuperHero构造函数的原型对象,因此在创建SuperHero实例时,它将继承Person的所有原型属性,以及任何原型属性直接添加到SuperHero原型对象。

答案 1 :(得分:1)

它与文档状态完全相同:

  

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

在这种情况下,protoPerson

该参数说明如下:

  

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

您的代码Object.create( Person.prototype );会返回一个对象,该对象会复制某人的属性(在本例中为firstName,lastName和gender)并将其分配给SuperHero。

请注意PersonSuperHero之间的相似之处,它们都包含firstNamelastName。另请注意差异,Person包含gender属性,而SuperHero包含powers属性。

答案 2 :(得分:1)

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

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

SuperHero.prototype = new Person();

我不喜欢专门链接原型,因为这意味着两个原型交织在一起,我更喜欢有一个是SubClass,一个是SuperClass。

自己看待它们的好方法是做这样的事情。在这里,您可以真正看到SuperHeroPerson获得的继承。请注意,它具有所有属性(first / last / etc),并且它是额外的Powers。

jsFiddle demo

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 ); ​