ES5中的this案例
1. 全局环境中的this
console.log(this === window); // 在浏览器中输出 true
function globalFunction() {
console.log(this === window); // 同样输出 true
}
globalFunction();
2. 函数中的this(非严格模式)
function myObject() {
this.value = "Hello";
function method() {
console.log(this.value); // 这里的this指向全局对象(window),因为method是单独调用的
}
method(); // 输出 undefined(如果value不是全局变量的话)
}
var obj = new myObject(); // 使用new时,myObject内的this指向新创建的对象
3. 严格模式下的函数this
function strictFunction() {
console.log(this === undefined); // 输出 true
}
strictFunction();
4. 回调函数中的this
var obj = {
value: "Hello",
method: function() {
setTimeout(function() {
console.log(this.value); // 这里的this指向全局对象(window),因为setTimeout的回调是单独调用的
}, 1000);
}
};
obj.method(); // 输出 undefined(如果value不是全局变量的话)
ES6中的this案例
1. 箭头函数中的this
var obj = {
value: "Hello",
method: function() {
setTimeout(() => {
console.log(this.value); // 这里的this继承自外围作用域 (即method函数中的this),输出 "Hello"
}, 1000);
}
};
obj.method();
注意箭头函数中this是静态的,this 始终指向函数声明时所在作用域下的this的值
箭头函数的使用
function getName(){
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
//设置 window 对象的 name 属性
window.name = '尚硅谷';
const school = {
name: "ATGUIGU"
}
//直接调用
getName(); //尚硅谷
getName2(); //尚硅谷
//call 方法调用
getName.call(school); // 尚硅谷
getName2.call(school); //报错
2. 类中的this
class MyClass {
constructor() {
this.value = "Hello";
}
method() {
console.log(this.value); // 这里的this指向类的实例
}
arrowMethod = () => {
console.log(this.value); // 箭头方法中的this也指向类的实例
}
}
var instance = new MyClass();
instance.method(); // 输出 "Hello"
instance.arrowMethod(); // 输出 "Hello"