我正在阅读有关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 );
做了什么?
答案 0 :(得分:4)
它创建一个继承自Person
构造函数原型对象的新对象。
就像你这样做一样。
SuperHero.prototype = new Person();
除了创建Person
实例而不实际调用Person
构造函数中的代码。
此对象用作SuperHero
构造函数的原型对象,因此在创建SuperHero
实例时,它将继承Person
的所有原型属性,以及任何原型属性直接添加到SuperHero
原型对象。
答案 1 :(得分:1)
它与文档状态完全相同:
使用指定的原型对象创建一个新对象 属性。
在这种情况下,proto
为Person
:
该参数说明如下:
该对象应该是新创建的对象的原型。
您的代码Object.create( Person.prototype );
会返回一个对象,该对象会复制某人的属性(在本例中为firstName,lastName和gender)并将其分配给SuperHero。
请注意Person
和SuperHero
之间的相似之处,它们都包含firstName
和lastName
。另请注意差异,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。
自己看待它们的好方法是做这样的事情。在这里,您可以真正看到SuperHero
从Person
获得的继承。请注意,它具有所有属性(first / last / etc),并且它是额外的Powers。
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 );