我正在使用节点v0.10.28
我一直试图将函数bind()
方法模拟为函数的原型,但遇到了一个奇怪的问题。
Function.prototype.bind = function() {
var obj = arguments[0],
argumentsArray = [],
self = this;
// since arguments is an object and we can't call .splice() on it
for(var i in arguments) {
argumentsArray.push(arguments[i]);
}
argumentsArray.splice(0,1);
// The following throws error when running via node, works fine on browser
//console.log(argumentsArray);
return function() {
return self.apply(obj,argumentsArray);
}
};
function sum(y,z) {
return this.x + y + z;
}
var obj = { x : 8},
f, value;
f = sum.bind(obj,1,2);
value = f();
console.log(value);
请参阅此小提琴,当我通过node(node demo.js
)运行时,它具有一些奇怪的行为。参见console.log(argumentsArray)
小提琴中的注释,取消注释,将其保存在文件中并通过node运行将给您以下错误:
TypeError: Object #<Object> has no method 'log'
console.log(value)
通过节点运行final时,final也不会在控制台上显示任何内容。似乎在浏览器上也可以正常工作。
我缺少什么,还是节点不允许console.log()
在原型函数定义之内或其他?
我在这里先向您的帮助表示感谢。
这是因为console
模块将其所有方法绑定到自身(请参见此处的源代码)。这是为您可以做的事情:
var log = console.log;
log('something');
console
模块将在首次使用时初始化。所以在线
// The following throws error when running via node, works fine on browser
console.log(argumentsArray);
node
将尝试初始化console
模块,然后调用log
方法。在模块初始化过程中,它将尝试在此处将log
方法绑定到自身,结果-将再次调用您的方法。模块将被视为已初始化,并且节点将尝试调用其方法。但是实际上当时还没有初始化。因此将引发错误。bind
console
log
console
PS:
对您要执行的操作的简单得多的实现:
Function.prototype.bind = function(context) {
var args = [].slice.call(arguments, 1);
var self = this;
return function() {
return self.apply(context, args.concat([].slice.call(arguments)));
};
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句