基本/高效JavaScript中的原型继承?

Pre*_*fix 1 javascript prototypal-inheritance

所以我目前有以下代码片段.我正在尝试创建一个Cylon包含模型属性和原型attack()方法的类.我正在创建一个HumanSkin继承自的类Cylon,并且还添加了自己的原型infiltrate()方法.

function Cylon(model){
  this.model = model;
}

Cylon.prototype.attack = function(){
    return("Destroy all humans!");
}

function HumanSkin(){}
HumanSkin.prototype = new Cylon();
HumanSkin.prototype.infiltrate = function(){
  return("Infiltrate the colonies");
}

cylon = new Cylon("raider");
caprica = new HumanSkin(6);
Run Code Online (Sandbox Code Playgroud)

我的问题是这个 - 为什么要console.log(caprica.model);回来Undefined?如何在JS中轻松获得完全继承(最好使用封装)?

the*_*eye 5

当你说,

HumanSkin.prototype = new Cylon();
Run Code Online (Sandbox Code Playgroud)

您正在Cylon使用空模型(undefined)创建一个新对象.因此,继承Cylon,可以像这样改进

HumanSkin.prototype = Object.create(Cylon.prototype);
Run Code Online (Sandbox Code Playgroud)

请注意,当您继承原型继承时,prototype父级的任何内容都将可供子级使用.但是modelCylon构造函数中.通常,这可以像这样解决

function HumanSkin(model) {
    Cylon.call(this, model);
}
Run Code Online (Sandbox Code Playgroud)

现在,每当构造一个新HumanSkin对象时,Cylon将使用当前对象(this)调用内部函数,model并将其作为参数传递给它.所以,Cylon将初始化model当前对象.