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

标签 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 ); 是做什么的?

最佳答案

它创建一个继承自 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/

相关文章:

javascript - 在 JS 变量中传递 '+' 符号

javascript - Angularjs - 将数据传递给工厂方法不起作用

javascript - jquery日历问题

javascript - jQuery Mobile 内部页面问题

C语言的Javascript编译器?

javascript - Ember JSON 加载问题 - 加载路线时出错 : undefined

javascript - jQuery Perfect Scroll——将滚动条设置到容器底部

javascript - indexedDB objectStore.get() 总是返回 undefined,尽管在 DB 中有结果

javascript - 我想将行号添加到我网站上的代码示例中。我想通过 CSS(生成的内容?)或 javascript 来做到这一点

javascript - Jquery 向 DOM 对象附加额外的#