1、JavaScript 中 This 的指向
一、普通函数中的 this
var name = "蛮王", position = "上单";
var obj = {
name: "寒冰射手",
objPosition: this.position,
relationFun: function () {
console.log(this.name + "的位置是:" + this.position);
}
};
console.log(obj.objPosition); // 上单
obj.relationFun(); // 寒冰射手的位置是:undefined
总结:
在普通函数中的this:
1、this 总是代表它的直接调用者(js 的 this 是执行上下文),例如:obj.relationFun,那么 relationFun 中的 this 就是 obj
2、在默认情况下,没有找到直接调用者,则 this 指向的是 window
再举例验证一下:
var hero = "盲僧";
function show (){
console.log(this.hero); // 此时 this 指向 window
}
show(); // 盲僧
function show (){
var hero = "盲僧";
console.log(this.hero); // 此时 this 指向 window, 在 window 未找到 hero
}
show(); // undefined
看到这里,普通函数中的 this 的指向问题,是不是就清晰很多了呢。
二、构造函数中的 this
来一起看下构造函数中的 this 指向问题吧,举例:
function lolFun() {
this.hero = "亚索";
}
var object = new lolFun;
console.log(object.hero);
看到这个例子,咱们先讲个题外话。弱弱的问一句:函数是对象吗?
答案是肯定的。当然了,我们也可以验证一下
lolFun instanceof Object // true
无论学习什么知识,凡事多问几个 “为什么” ?我相信,你将进步的很快!
那我们不妨再大胆一点问:对象是通过函数创建的吗?
答案也是肯定的。当聊到这里,估计会有小伙伴该有疑问了,那举例简单验证一下吧。
大多数情况下,我们是这样创建对象的:
var obj = {
name: "亚索",
position: "中单",
}
但实际上它底层上也是用函数创建的:
var obj = new Object();
obj.name = "亚索";
obj.position = "中单";
此时的 Object 是函数 (function)
typeof Object // function
关于函数与对象的关系,简单总结一下:对象是通过函数创建的,而函数又是一种对象
function lolFun() {
this.hero = "亚索";
}
var object = new lolFun;
console.log(object.hero); // 亚索
OK,言归正传,继续讨论构造函数中的 this 指向。
这里能打印出来: “亚索”,按照 普通函数中 this 总结的两条,好像没法解释了,其实:
new 关键字是能够改变指针指向的。通过 new 关键字实例化,得到 object 对象,同时会将 lolFun 中的属性或者函数 “复制” 一份到 object 对象中。所以在 object 中找到了 hero 属性,自然就输出了:”亚索”。
其实,这样理解是可以的。但是,理解是不完整的,继续举例:
举例1:
function lolFun() {
this.hero = "亚索";
return {};
}
var object = new lolFun;
console.log(object.hero); // undefined
举例2:
function lolFun() {
this.hero = "亚索";
return function () { };
}
var object = new lolFun;
console.log(object.hero); // undefined
举例3:
function lolFun() {
this.hero = "亚索";
return true;
}
var object = new lolFun;
console.log(object.hero); // 亚索
举例4:
function lolFun() {
this.hero = "亚索";
return null;
}
var object = new lolFun;
console.log(object.hero);// 亚索
总结:
构造函数中的 this
1、如果返回了对象,则 this 指向的就是这个对象;如果无返回值或者返回值的不是对象,则 this 还是指向函数的实例
2、【特殊记忆】从举例4,可以得出结论,虽然 null 是对象,但是 this 还是指向函数实例了