Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between _.extend(Something.prototype, someObj) and Something.prototype.someFunc = someFunc?

I'm getting into actual object oriented programming using JavaScript and i've run into two different ways of extending the prototype of an existing object.

Method one:

Something.prototype.someFunc = function() {
    // To something usefull
}

Method two (using underscore.js):

_.extend(Something.prototype, {
    someFunc: function() {
        // Do the same but differently
    }
}

What is the difference between these two approaches? Which one is considered "better"? To me it looks like the first method is better because it uses plain old javascript, and the second method is someone elses implementation. But on the other hand, the underscore.js developers surely didn't add the _.extend() method for nothing?

like image 513
jaapz Avatar asked Mar 18 '13 10:03

jaapz


1 Answers

They are equivalent functionally. In the case of a single method, I think method one is more readable, but in the case of multiple methods added to the same prototype, method two might be more readable (this is of course subjective).

RE: The underscore.js developers surely didn't add the _.extend() method for nothing:

_.extend has other uses, such as default options:

function (options) {
  options = _.extend({ height: 80, width: 20 }, options);
  ...
}
like image 148
Max Nanasy Avatar answered Nov 08 '22 00:11

Max Nanasy