What is the difference between _.extend(Something.

2020-05-27 16:44发布

问题:

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?

回答1:

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