我正在阅读 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 );
是做什么的?
最佳答案
它创建一个继承自 Person
构造函数原型(prototype)对象的新对象。
就像你这样做一样。
SuperHero.prototype = new Person();
只不过它创建了 Person
实例而实际上并没有调用 Person
构造函数中的代码。
这个对象作为SuperHero
构造函数的原型(prototype)对象,这样当你创建一个SuperHero
实例时,它会继承的所有原型(prototype)属性Person
,以及直接添加到 SuperHero
原型(prototype)对象的任何原型(prototype)属性。
关于javascript - Object.create( Class.prototype ) 在这段代码中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12375194/