Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inheritance with _.extend()

Tags:

javascript

oop

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

enter image description here

underscoreJS

enter image description here

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 ...

enter image description here

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

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

like image 835
Jiew Meng Avatar asked Dec 05 '12 10:12

Jiew Meng


People also ask

What is _ Extend?

The _. extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.

How do you use extends in JavaScript?

The extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.

How can I get multiple inheritance in JavaScript?

const objects = multiple( { foo: 1 }, { bar: 2 }, { baz: 3 } ); So we can pass multiple objects and then copy the properties by using the spread operator. Similar work can be done using mixins. Mixins are some objects that can be incorporated into some other objects.

What is inheritance in JavaScript with example?

Inheritance is a useful feature that allows code reusability. In the above example, the Student class inherits all the methods and properties of the Person class. Hence, the Student class will now have the name property and the greet() method.


1 Answers

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.

like image 125
rdiazv Avatar answered Oct 15 '22 01:10

rdiazv