Javascript里面的this
上下文对象
在Javascript中,你的代码总是有一个上下文对象(代码处在该对象内),这是面向对象语言的常见特点。上下文对象是通过this变量来体现的,这个变量永远指向当前代码所处的对象中。
例子:
var obj = {
yes: function(){
// this == obj
this.val = true;
},
no: function(){
this.val = false;
}
};
// We see that there is no val property in the 'obj' object
alert( obj.val == null );
// We run the yes function and it changes the val property
// associated with the 'obj' object
obj.yes();
alert( obj.val == true );
// However, we now point window.no to the obj.no method and run it
window.no = obj.no;
window.no();
// This results in the obj object staying the same (as the context was
// switched to the window object)
alert( obj.val == true );
// and window val property getting updated.
alert( window.val == false );
此代码中,我们把obj.no变量的上下文对象切换为window变量时,代码变得不好理解了。javascript提供了一套方法让这一过程变得更好了理解和实现,call和apply两个方法就用于实现此功能。
call和apply
call方法可改变上下文this指针,类似的方法还有apply,只是调用方式上有些不同:
call 方法
调用一个对象的一个方法,以另一个对象替换当前对象。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
参数 -
thisObj
可选项。将被用作当前对象的对象。
arg1, arg2, , argN
可选项。将被传递方法参数序列。
说明 -
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply方法
apply(thisArg,argArray);
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisArg任何一个参数,那么 Global 对象将被用作 thisArg, 并且无法被传递任何参数。
例子:
// A simple that sets the color style of its context
function changeColor( color ) {
this.style.color = color;
}
// Calling it on the window object, which fails, since it doesn't
// have a style object
changeColor( "white" );
// Find the element with an ID of main
var main = document.getElementById("main");
// Set its color to black, using the call method
// The call method sets the context with the first argument
// and passes all the other arguments as arguments to the function
changeColor.call( main, "black" );
// A function that sets the color on the body element
function setBodyColor() {
// The apply method sets the context to the body element
// with the first argument, the second argument is an array
// of arguments that gets passed to the function
changeColor.apply( document.body, arguments );
}
// Set the background color of the body to black
setBodyColor( "black" );
技巧
在某种情况下,我们需要在callback函数里面引用定义这个callback函数时的上下文对象,可以采取下面的方法:
MainFrame = function(){
};
MainFrame.prototype = new MainFrame();
MainFrame.prototype.hideDialog = function(){
// TODO : hide the mainFrame dialog.
};
MainFrame.prototype.initContent = function(){
var me = this;
var cacelButtonClick = function(){
me.hideDialog();
}
};
参考:
- 精通JavaScript 作者: John Resig 译者: 江疆 / 陈贤安 出版社: 人民邮电出版社