以下题目中的this指向涉及:
-
谁调用这个函数, 函数内部的this值就指向谁
-
对象内部方法的this指向调用这些方法的对象,也就是谁调用就指向谁。
-
箭头函数的重要特征:箭头函数中没有this和arguments,箭头函数的this值是 函数定义的时候就确定下来了,就是上一层作用域的this值
var myName = 1;
var obj = {
myName: 2,
func: function (a) {
const b = 12;
console.log('0:', this === obj); // 这里是true 谁调用函数,函数中的this就指向谁
return {
myName: 3,
// 箭头函数的this值是 函数定义的时候就确定下来了,就是上一层作用域的this值
getName1: () => {
console.log('1:', this); // 所以这里的this值是 obj
console.log('2', this.myName); // 2
},
getName2: function () {
console.log('3:', this); // return 出来的这个对象
console.log('4', this.myName); // 3
},
};
},
};
// 谁调用函数, 函数内部的this值就指向谁
const fn = obj.func(1);
fn.getName1()
fn.getName2()