问题描述
Employee.prototype = Object.create(Person.prototype);
和
_.extend(Employee.prototype, Person.prototype);
两者都给出类似的结果(输出),但是下划线方法似乎将Person.prototype添加到Employee.constructor.prototype,并且在这里和那里相当多的东西,为什么?
Both give similar results (output), but the underscore method seems to add the Person.prototype to the Employee.constructor.prototype, and quite abit extra stuff here and there, why?
纯JS
underscoreJS
underscoreJS
_的一个很好的副作用_ .extend
我可以很容易地进行多重继承:看起来它也不会使原型链变得更长......
A nice side effect of _.extend
is I can easily do multiple inheritance: seems like it doesnt make the prototype chain longer too ...
_.extend(Employee.prototype, Person.prototype);
_.extend(Employee.prototype, {
doSomething: function() {
return "hi ...";
}
});
但是......
为什么有2个sayHi和doSomething功能? (实际上,当我只做1次延伸时它是一样的)。
Why is there 2 sayHi and doSomething functions? (actually its the same when I just do 1 extend).
http://jsfiddle.net/VMqSy/1/
推荐答案
使用 Employee.prototype = Object。 create(Person.prototype);
您正在完全替换 Employee.prototype
。
但是使用 _.extend(Employee.prototype,Person.prototype);
您要添加 Person.prototype
顶部的 Employee.prototype
。
But with _.extend(Employee.prototype, Person.prototype);
you are adding the Person.prototype
on top of the Employee.prototype
.
例如,
var a = {var1:1, var2:2};
var b = {var2:4, var3:3};
console.log(_.extend(a, b)); // {var1:1, var2:4, var3:3}
如您所见, a
它没有完全被 b
取代,它只是扩展由<$ c中定义的属性$ C> b 。
As you see, a
it's not completely replaced by b
, it's just extended by the properties defined in b
.
这篇关于使用_.extend()进行JavaScript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!