开发者

Are these ways of writing function prototype equivalent?

I have always used to write function prototype declaration i开发者_如何学编程n 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 () {}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜