在JavaScript中进行原型设计时,首选哪种方法?

And*_*y F 2 javascript prototype

这是一个人为的例子:

我想划分两个数字,我需要写一个方法来做到这一点.我可以这样写:

function divide(dividend,divisor) {
    return dividend/divisor;
};

//Assign the result of the divide function to an element on the page.
$(".firstanswer").html(divide(6,2));
Run Code Online (Sandbox Code Playgroud)

我也可以写这样的东西:

Number.prototype.dividedBy = function (divisor)? {
    var dividend = this;
    return dividend/divisor;
};

var six = 6;
var two = 2;
$(".secondanswer").html(six.dividedBy(two));
Run Code Online (Sandbox Code Playgroud)

这两种方法都有相同的答案,所以我想知道的是:
使用这两种方法有什么优点或缺点.是否有显着的性能(负载/运行时间)差异?在内存影响方面,是否比另一个更可重用?理解的容易程度如何?最终,对于一个像这样简单的例子,它是否重要?

我还创建了一个小提琴,因为代码更好.

Bla*_*ter 7

第一种方法没有缺点(除了不同的语法)

在第二种方法中,您冒着实施的风险,如果它成为一部分NumberMath对象或其他具有相同功能名称的第三方库:)

虽然通常要避免它,但这样做:

Number.prototype.dividedBy = Number.prototype.dividedBy || function (divisor)? {
    var dividend = this;
    return dividend/divisor;
};
Run Code Online (Sandbox Code Playgroud)

这样,你说,如果已经存在该功能,则使用其他创建我自己的功能.


有关详细信息,请查看(@Kangax的另一篇精彩文章)