一、this 对象的产生
引用 阮一峰老师 的话:
this 它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
所以时刻提醒自己 this是在函数执行时被绑定的,不要被任何赋值语句打乱阵脚。
二、函数调用的方式
方法调用
也称对象属性的调用方式。this 指向obj
var obj = {
say:function(){
console.log("打印this:",this);
}
}
obj.say();
函数调用
例子 this 指向函数运行的上下文环境(window)
function say(){
...this
};
say();
构造函数调用
this 指向实例对象obj
function Say(){
...
}
var obj = new Say();
apply call bind模式
重定函数内部的this
三、例子巩固
var name = "window";
function outSay(){
console.log(this.name);
}
let obj = {
name: "obj",
name1: this.name,
say1: function () {
console.log("say1:", this.name);
},
say2: function () {
console.log("say2:", this.name1);
},
say3: function () {
setTimeout(function () {
console.log("say3:", this.name);
}, 0);
},
say4: function () {
setTimeout(() => console.log("say4:", this.name), 0);
},
say5: outSay,
say6:function(){
var fn = outSay;
fn();
}
}
console.log("obj.name:",obj.name);
console.log("obj.name1:",obj.name1);
obj.say1();
obj.say2();
obj.say3();
obj.say4();
obj.say5();
obj.say6();
思考几分钟,再看结果:
代码分析:
var name = "window";
function outSay(){
console.log(this.name);
}
let obj = {
name: "obj",
//this指向window
name1: this.name,
say1: function () {
console.log("say1:", this.name);
},
say2: function () {
console.log("say2:", this.name1);
},
say3: function () {
setTimeout(function () {
console.log("say3:", this.name);
}, 0);
},
say4: function () {
setTimeout(() => console.log("say4:", this.name), 0);
},
//say5() 是方法调用
say5: outSay,
//say6() 是方法调用
say6:function(){
var fn = outSay;
//fn()实际是函数调用
fn();
}
}
console.log("obj.name:",obj.name); //obj
console.log("obj.name1:",obj.name1); //window name1赋值语句中的this是window
obj.say1(); // 方法调用:this指向obj:obj
obj.say2(); // 方法调用:this指向obj: window
obj.say3(); // 方法调用-->异步函数回调函数-->函数调用上下文是window:window
obj.say4(); // 方法调用-->异步函数回调函数-->箭头函数调用上下文是obj:obj
obj.say5(); // 方法调用this指向obj对象:obj
obj.say6(); // 方法调用 --> 函数调用 -->上下文是window:window
有点疑惑的可能:
- 字面量对象里的 this 指向 window;
- obj.say6() 的执行结果: 函数的执行时 fn() fn()属于函数调用,那就看fn运行的上下文:window
时刻提醒自己 this是在函数执行时被绑定的,不要被任何赋值语句打乱阵脚。