最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oop - JavaScript inheritance with _.extend() - Stack Overflow

programmeradmin2浏览0评论

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?

pure JS

underscoreJS

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 ...";
    }
});

But ...

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

/

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?

pure JS

underscoreJS

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 ...";
    }
});

But ...

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

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

Share Improve this question asked Dec 5, 2012 at 10:42 Jiew MengJiew Meng 88.2k191 gold badges522 silver badges831 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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

But with _.extend(Employee.prototype, Person.prototype); you are adding the Person.prototype on top of the Employee.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, a it's not completely replaced by b, it's just extended by the properties defined in b.

发布评论

评论列表(0)

  1. 暂无评论