首页 > class.prototype.foo=function foo 这样写的用意是什么

class.prototype.foo=function foo 这样写的用意是什么

在nodejs的源码中看到这样的写法class.prototype.foo=function foo,想问问这样的的用意是什么?

EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || isNaN(n))
    throw new TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

我的问题是问什么还要在function后面再声明一次函数名

// 为什么不这样写,而要在多声明一次
EventEmitter.prototype.setMaxListeners = function (n) {
  if (typeof n !== 'number' || n < 0 || isNaN(n))
    throw new TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

今天google了下,大概知道其中的部分原因

  1. 首先这样写的目的不是为了在文件同时声明一个同名的函数,例子如下

    var foo = function() {};
    foo.prototype.fn = function fn() {};
    
    fn(); // ==> fn is not defined(…)
  2. 如同 @Dappur 所回答的,这样写的目的可以方便调试
    具体的回答可以看看这个js返回一个匿名函数和声明一个函数后在返回有什么区别?。虽然不是我所问的这个问题的情景,但原理还是类似的


我所能想到的就是,在调试的时候,调用栈(Call Stack)中会显示setMaxListeners而非(anonymous function),方便调试吧


感觉没有差别。

楼上说“匿名函数和具名函数的区别”,我测试了一下。

String.prototype.say = function say() {
  alert("hi");
}

String.prototype.say();    // hi
"ok".say();    // hi
say();    // say is not defined

可以发现多声明一次没有影响。


匿名函数和具名函数的区别吧


这种用意就是你的EventEmitter里面有一个函数变量setMaxListeners,然后就可以这样用了:

var emitter = new EventEmitter();
emitter.setMaxListeners(100);

这就是想把js当成面向对象语言用,类似Java的类和成员函数


起到注释的作用吧。

【热门文章】
【热门文章】