原文链接:http://dbear.iteye.com/blog/609090
------------------------------------------------------------------------
首先我们需要知道,function的invoke方式主要有三种:1、单纯调用 2、作为某对象的method被调用 3、apply()和call()调用。针对三种不同的invoke方式,"this"拥有不同的指向:当function被作为单纯的function启动时,那么“this”指向的是global object;当function是某个object的method,并由该object作为方法来启动时,“this”指向调用该function的那个object;使用apply()和call()方法调用时,function中的"this"指向的是这两个方法中的作为第一个参数的那个对象。
1. ordinary invoke
var testVar = 20;
function test() {
var testVar = 40;
document.write (this.testVar); // 20 is printed,"this" refers to global object
}
test();
2. method invoke
var testVar = 20;
function test() {
var testVar = 30;
var o = {testVar: 60,
methodFunc: function(){
this.testVar = 70; //when the function invoked, “this” refers to o
}};
o.methodFunc();
document.write(testVar + "<br>"); //print 30
document.write(o.testVar + "<br>"); //print 70, property of o has been changed
document.write(this.testVar + "<br>"); //print 20, property of global object remains as
}
test();
3. nested function in a method---ordinary invoke
var testVar = 20;
function test5() {
var testVar = 30;
var o = {testVar: 60,
methodFunc: function(){
this.testVar = 70;
(function(){
this.testVar = 40;
})();
}};
o.methodFunc();
document.write(testVar + "<br>"); //30
document.write(o.testVar + "<br>"); //70, this refers to object o
document.write(this.testVar + "<br>"); //40, this refers to global object !!!!Confusing ha? But it's true!!!
}
test5()
4. invoked by call() and apply()
function bindedFunc() {
this.testVar = 40;
}
function test() {
var testVar = 20;
var o = {testVar: 30};
bindedFunc.apply(o);
document.write(o.testVar) //prints 40
}
test();