ES6的箭头函数,箭头函数不会创造块作用域,无法生成一个独立的环境,this指向上层的this

发布时间 2023-11-14 18:44:06作者: 龙陌
var color = 'green';
var test4399 = {
    color: 'blue',
    getColor: function(){
        var color = "red";
        alert(this.color);
    }
}
var getColor = test4399.getColor;
getColor();
test4399.getColor();

以上 JavaScript 代码执行后, 浏览器 alert 出来的结果分别是

A
undefined,red

B
green,blue

C
undefined,blue

D
green,undefined

E
blued,undefined

正确答案:B

1.getColor() var getColor = test4399.getColor;
即var getColor = function(){var color = "red";alert(this.color);};
执行getColor()函数时this指向的window,因为window.color为green,所以弹出green

2.test4399.getColor(),此时this指向的是test4399,test4399.color为blue,所以弹出blue

getColor();相当于普通的函数调用,此时this指向window,this.color应该为全局变量的值

test4399.getColor();此时this指向调用函数的对象test4399,因此this.color应该为对象的属性值

这题的重点只是this关键字的用法,指向运行时的对象,而不是定义时的对象,表示函数的运行时。
作为总结:
1、函数作为对象的方法被调用,this指向调用者!
2、用于构造函数,this指向新对象
3、ES6的箭头函数,箭头函数不会创造块作用域,无法生成一个独立的环境,this指向上层的this