这不是关于性能,而是关于访问对象的特定实例的属性:-
x.init()
如果您没有在函数中使用this,则不会显示“测试”。
实际上上面的行是相同的:-
x.init.call(x);
call使用中的第一个参数在函数执行时赋值给this。
现在考虑:-
var fn = x.init; //Note no () so the function itself is assigned to the variable fn
fn();
现在您在警报中什么也得不到。这是因为上面是有效的:-
fn.call(window);
在浏览器托管的 Javascript 中,window 对象与全局对象同义。当“原始”调用函数时,this 默认为全局对象。
典型的错误是这样的:-
var x = {
ele: 'test';
init: function(elem) {
elem.onclick = function() { alert(this.ele); }
}
}
x.init(document.getElementById('myButton'));
但是这不起作用,因为附加到 onclick 事件的函数是由浏览器使用如下代码调用的:-
onclick.call(theDOMElement)
因此,当函数运行时this 并不是你想象的那样。
我通常对这种情况的解决方案是:-
var x = {
ele: 'test';
init: function(elem) {
var self = this;
elem.onclick = function() { alert(self.ele); }
elem = null;
}
}
x.init(document.getElementById('myButton'));
注意elem = null 是 IE 内存泄漏解决方法。