var color = 'green'; var test4399 = { color: 'blue', getColor: function(){ var color = "red"; alert(this.color); } } var getColor = test4399.getColor; getColor(); test4399.getColor();
以上 JavaScript 代码执行后, 浏览器 alert 出来的结果分别是
var color = 'green'; var test4399 = { color: 'blue', getColor: function(){ var color = "red"; alert(this.color); } } var getColor = test4399.getColor; getColor(); test4399.getColor();
undefined,red
green,blue
undefined,blue
green,undefined
blued,undefined
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