ES6/7学习之this
程序员文章站
2023-12-21 21:34:52
...
正常函数声明中this指向调用函数的对象
var name = '乔峰';
function show() {
console.log(this.name);
}
show(); // 此处调用函数的对象是全局(window),所以输出:乔峰
var person = {
name: '虚竹',
show: function() {
console.log(this.name)
}
};
person.show(); // 此处调用函数的对象是person,所以输出:虚竹
var other = person.show;
other(); // other将引用指向person.show,所以此处调用函数的对象又是全局(window),所以输出:乔峰
箭头函数中this指向创建函数时的上下文的this
var name = '乔峰';
function Person() {
this.name = '虚竹';
(function() {
console.log(this.name);
})();
}
var person = new Person(); // 乔峰
var obj = {
name: '段誉',
show: function() {
console.log(this.name);
}
};
obj.show(); // 段誉
var name = '乔峰';
function Person() {
this.name = '虚竹';
(() => {
console.log(this.name);
})();
}
var person = new Person(); // 虚竹
var obj = {
name: '段誉',
show: () => {
console.log(this.name);
}
};
obj.show(); // 乔峰
严格模式下,this默认不指向全局对象window(this===undefined),但在最外层上下文创建的箭头函数可以指向window
"use strict"
var name = '乔峰';
var obj = {
name: '段誉',
show: function() {
console.log(this.name);
}
};
obj.show(); // 段誉
function Person() {
this.name = '虚竹';
(function() {
console.log(this.name);
})();
}
var person = new Person(); // 报错:Cannot read property 'name' of undefined
"use strict"
var name = '乔峰';
function Person() {
this.name = '虚竹';
(() => {
console.log(this.name);
})();
}
var person = new Person(); // 虚竹
var obj = {
name: '段誉',
show: () => {
console.log(this.name);
}
};
obj.show(); // 乔峰