Ret*_*n-1 10 javascript prototype
我已经看到,在许多情况下,js中的继承可以像这样实现
function Organism(age) {
this.age = age;
}
Organism.prototype.growOlder = function(){ this.age = this.age + 1}
var org = new Organism("1000");
function Human(name,age){
Organism.call(this,age); //this sets up the properties on the human object
this.name = name;
}
Human.prototype = Object.create(Organism)
Human.prototype.constructor = Human; //sets the constructor
Human.prototype.run = function(){ console.log(this.name + "run")}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果有人可以详细解释为什么Object.create(Organism)是必要的,只是这样做
Human.prototype = Organism.prototype
Run Code Online (Sandbox Code Playgroud)
是不够的.原型链看起来像
没有object.create:
Human.__proto__ -> Organism __proto__-> Object
with object.create:
Human.__proto__-> IntermediateObject.__proto__ -> Organism.__proto__-> Object
感谢您的时间.
编辑:我知道es6类并继承语法糖.我只是好奇如何在较低的层面上工作.
我的问题是,是否有人可以详细解释为什么 Object.create(Organism) 是必要的,并且简单地执行此 Human.prototype = Organism.prototype 是不够的。
你完全可以做到这一点,而且它甚至会起作用。
然而,有一个微妙的问题。如果您直接分配,它将继承您在 上创建的所有方法,Organism.prototype从而产生令人讨厌的副作用。不是你想要的。OrganismHuman.prototype
例如,如果您Human.prototype = Organism.prototype这样做,那么org将会有run,但它可能不应该有 Human 的方法。