antonjs
antonjs

Reputation: 14318

Are these ways of writing function prototype equivalent?

I have always used to write function prototype declaration in this way:

var O = function () {};
O.prototype.fn = function () {}

But Some developer write in this way:

var O = function () {};
O.prototype.fn = function fn () {}

Are these way equivalent? If not, what is the advantage for using the second way?

var O = function () {};
O.prototype.fn = function fn () {}

Upvotes: 3

Views: 140

Answers (2)

Raynos
Raynos

Reputation: 169391

var a = function _a() { }

vs

var a = function () { }

The former is called a named function expression,

The latter is just a function assignment.

A NFE has two advantages

  • It has a name which is shown in a stack trace. This improves debugging significantly
  • It has a name you can use within the function for recursion

A NFE has disadvantages. Kangax talks about them in depth.

Personally I use NFE everywhere and ignore the memory leaks IE makes. However since IE leaks these function names into global scope, an effort should be made to make them unique.

Because IE has a habit of leaking these names into global scope, I try to make them unique.

This is why I prepend function declaration names with _

var doSomeLogic = function _doSomeLogic() {

};

As a side-note there's an alternative pattern to

var O = function () {};
O.prototype.fn = function fn () {}

var obj = new O();

Which is

// prototype object
var O = {
    fn: function _fn() { }
};
// factory
var o = function _o() { return Object.create(O); }

var obj = o();

Upvotes: 4

Guffa
Guffa

Reputation: 700302

If you use a name when you create an anonymous function, you can use that name inside the function:

var x = function y() {
  y(); // here it exists
}

y(); // here it doesn't exist

The use for that is of course limited. You can use it for recursion, or if you hook up the method as a callback function.

Upvotes: 0

Related Questions