_.extend(Something.prototype,someObj)和Something.prototype.someFunc = someFunc有什么区别? [英] What is the difference between _.extend(Something.prototype, someObj) and Something.prototype.someFunc = someFunc?

查看:104
本文介绍了_.extend(Something.prototype,someObj)和Something.prototype.someFunc = someFunc有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript进入实际的面向对象编程,并且我遇到了两种不同的扩展现有对象原型的方法。

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.

方法一:

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

方法二(使用underscore.js):

Method two (using underscore.js):

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

这两种方法有什么区别?哪一种被认为是更好?对我来说它看起来很像像第一种方法更好,因为它使用普通的旧javascript,第二种方法是别人的实现。但另一方面,underscore.js开发人员肯定没有添加_.extend()方法什么?

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?

推荐答案

它们在功能上是等同的。在犯罪的情况下gle方法,我认为方法一更具可读性,但在多个方法添加到同一原型的情况下,方法二可能更具可读性(这当然是主观的)。

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:underscore.js开发人员肯定没有添加_.extend()方法:

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

_.extend有其他用途,例如默认选项:

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

function (options) {
  options = _.extend({ height: 80, width: 20 }, options);
  ...
}

这篇关于_.extend(Something.prototype,someObj)和Something.prototype.someFunc = someFunc有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆