1、谁作为调用者就指向谁
function a() {
console.log(this);
}
//下面a方法的调用,其实在js中等于window.a(),也就是window调用了a()方法,所以a方法中的this指向了window
a(); //this指向window对象
/*下面这方法其实将a方法赋值给了b对象的say方法,调用say方法(也就是a方法)的是b对象,所以此时this指向b对象。
你可能会说b.say()不就等于window.b.say()方法吗?为什么不是this不是指向window呢?
其实在下面这个环境b对象是当前window下的一个属性。调用say方法的是b对象。所以this是指向b的
*/
var b = {};
b.say = a;
b.say(); //此时的this指向了b对象
2、没有拥有者,直接调用,就指向window
function a() {
console.log(this);
}
3、另外一个例子
我们在js中可以使用document.write()方法向网页中输入文本内容。如
document.write("aaaa"); 网页中就会被加入aaaa文本。
但是如果我们像下面这么写呢?
var myWrite = document.write;
myWrite("aaaa");
上面的代码首先是我将document.write方法赋值给myWrite方法。然后使用myWrite()方法向网页中输入文本内容。但是这里会报错,为什么呢?
原因就在这个write方法的this指针的域被改变啦!
document.write()方法的this是指向document的。所以可以向网页中输入文本内容
但是我们将document.write方法赋值给myWrite对象,然后在调用myWrite()方法。调用myWrite()方法的对象域是全局变量window,
相当于window.myWrite()。此时this指向window,而不指向document.所以会报错。
4、遇到上面的this域被改变了,我们怎么办呢?
改变this域的三个方法bind()、call()、apply()。这三个方法js所有的Function对象都具有
4.1 使用bind方法
a.bind(b); 就是将a()方法的this指针的作用域绑定到b对象的作用域上,也就是现在a的this指针的作用域就是b
如是上面的代码就可以改成:
document.write("aaaa");
var myWrite = document.write;
myWrite.bind(document)("aaaa"); //网页中输入aaaa。此时的this指针指向了bind()的document。
4.2 使用call方法
call(a, b); a是当前方法需要执行的 域,后面的b是当前方法的参数,可以传多个参数,多个 参数直接用逗号隔开即可,如 call(a, b, c, d); b, c, d都是方法的参数
上面的代码用call来改写就是:
document.write("aaaa");
var myWrite = document.write;
myWrite.call(document, "aaaa");
4.3 使用apply方法
apply(a, b) a是当前方法需要执行的域,后面的b是当前方法的参数,可以传多个参数,多个参数需要使用数组来传入。如apply(a, [b, c, d]);b、c、d为参数
上面代码用apply来改写就是:
document.write("aaaa");
var myWrite = document.write;
myWrite.call(document, "aaaa");
5、思考:
代码片段一
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //指向其中的this指向window,因为没有拥有者,所以结果就是"The Window"
代码片段二
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
//在getNameFunc方法中将this绑定到that对象上,而that属于getNameFunc函数的内部变量,而这个函数的执行域是object。所以结果是"My Object"
alert(object.getNameFunc()());