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

我正在阅读有关 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构造函数的原型对象继承的新对象.

就像你这样做一样.

SuperHero.prototype = new Person();

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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...