JavaScript 继承与 _.extend()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13721367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:36:16  来源:igfitidea点击:

JavaScript inheritance with _.extend()

javascriptoop

提问by Jiew Meng

Whats the difference between

有什么区别

Employee.prototype = Object.create(Person.prototype);

and

_.extend(Employee.prototype, Person.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?

两者都给出了相似的结果(输出),但是下划线方法似乎将 Person.prototype 添加到 Employee.constructor.prototype 中,并且到处都有很多额外的东西,为什么?

pure JS

纯JS

enter image description here

在此处输入图片说明

underscoreJS

下划线JS

enter image description here

在此处输入图片说明

A nice side effect of _.extendis I can easily do multiple inheritance: seems like it doesnt make the prototype chain longer too ...

一个很好的副作用_.extend是我可以轻松地进行多重继承:似乎它不会使原型链变得更长......

_.extend(Employee.prototype, Person.prototype);
_.extend(Employee.prototype, {
    doSomething: function() {
        return "hi ...";
    }
});

But ...

但 ...

enter image description here

在此处输入图片说明

Why is there 2 sayHi and doSomething functions? (actually its the same when I just do 1 extend).

为什么有 2 个 sayHi 和 doSomething 函数?(实际上,当我只做 1 个扩展时,它是一样的)。

http://jsfiddle.net/VMqSy/1/

http://jsfiddle.net/VMqSy/1/

回答by rdiazv

With Employee.prototype = Object.create(Person.prototype);you are completely replacing the Employee.prototype.

随着Employee.prototype = Object.create(Person.prototype);您完全取代Employee.prototype.

But with _.extend(Employee.prototype, Person.prototype);you are adding the Person.prototypeon top of the Employee.prototype.

但是随着_.extend(Employee.prototype, Person.prototype);Person.prototypeEmployee.prototype.

For example,

例如,

var a = {var1:1, var2:2};
var b = {var2:4, var3:3};
console.log(_.extend(a, b)); // {var1:1, var2:4, var3:3}

As you see, ait's not completely replaced by b, it's just extendedby the properties defined in b.

如您所见,a它并没有完全被 替换b,它只是被 中定义的属性扩展b