在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;
};
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我所能想到的就是,在调试的时候,调用栈(Call Stack)中会显示
setMaxListeners而非(anonymous function),方便调试吧这种用意就是你的EventEmitter里面有一个函数变量setMaxListeners,然后就可以这样用了:
这就是想把js当成面向对象语言用,类似Java的类和成员函数
起到注释的作用吧。
匿名函数和具名函数的区别吧
感觉没有差别。
楼上说“匿名函数和具名函数的区别”,我测试了一下。
可以发现多声明一次没有影响。
今天google了下,大概知道其中的部分原因
首先这样写的目的不是为了在文件同时声明一个同名的函数,例子如下
如同 @Dappur 所回答的,这样写的目的可以方便调试
具体的回答可以看看这个js返回一个匿名函数和声明一个函数后在返回有什么区别?。虽然不是我所问的这个问题的情景,但原理还是类似的