有很多问题和答案涵盖了这种技术,但我似乎无法找到所需的this
上下文为call()或apply()设置。如何在Array.prototype.slice.call(参数)中设置'this'上下文
我明白
Array.prototype.slice.call(arguments)
是有点相当于
arguments.slice()
与arguments
被转换成一个适当的数组对象,但如果我尝试使用这个约定,我自己对象不起作用。我试着写一个小的测试这样做:
var Logger = function(){};
Logger.prototype.print = function(msg){
console.log ((new Date()).getTime().toString() + msg);
};
(function(){
var o = {
name: "Hi Bob!",
};
var l = new Logger();
l.print(o.name); //works fine
Logger.prototype.print.call(o.name); //calls print method, but 'msg' is undefined
}());
是否有可以Array.prototype
或arguments
对象,允许该功能的应用程序没有必要的情况下工作,有些特别的问候?
不,只有你的代码“有点相当于”'o.name.print()' - 这显然不是你想要的。有关它的工作方式,请参阅http://stackoverflow.com/q/6763555/1048572。 – Bergi 2013-03-18 16:07:57