Andy F
Andy F

Reputation: 1517

Which method is preferred when prototyping in JavaScript?

Here's a contrived example:

I want to divide two numbers and I need to write a method for doing so. I could write something like this:

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

I could also write something like this:

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

var six = 6;
var two = 2;
$(".secondanswer").html(six.dividedBy(two));

Both methods yield the same answer, so what I'd like to know is this:
What are the advantages or disadvantages to using either method. Is there a significant performance (load/run time) difference? Is one more reusable than the other in terms of memory impact? What about ease of comprehension? Ultimately, for an example as simplistic as this, does it matter?

I've also created a Fiddle because code is better.

Upvotes: 2

Views: 139

Answers (1)

Blaster
Blaster

Reputation: 9080

There is no disadvantage in first method (except for different syntax)

In second method, you risk the implementation, what if it becomes part of Number or Math object or some other third party library having same function name :)

Though normally to avoid it, this is done:

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

This way, you say, if there is that function already present use that else create my own.


For more details, check out (yet another great article by @Kangax as always)

Upvotes: 6

Related Questions