具有以下代码,当我期望“this”关键字引用全局变量并在缺少 PlayGound 范围变量的情况下显示“Football”时,从我的对象实例调用 Play 方法时输出未定义。
var game = "Football";
function Play() {
console.log(this.game)
}
function PlayGround() {
this.Play = Play;
}
var obj = new PlayGround();
obj.Play();
现在,在构造函数级别调用 Play(),不传递它对局部变量的引用,输出为“Football”。
var game = "Football";
function Play() {
console.log(this.game)
}
function PlayGround() {
Play();
}
var obj = new PlayGround();
有人可以解释这两种方法表现不同的原因吗?
第一个输出 undefined
非常简单,因为 obj
没有 game
属性。可以这样修复:
var game = "Football";
function Play() {
console.log(this.game)
}
function PlayGround() {
this.game = game;
this.Play = Play;
}
var obj = new PlayGround();
obj.Play();
第二个片段是不好的做法,因为它依赖于 non-strict mode simple calls 的机制为了工作。
如果将第二个片段更改为严格模式,它将出错,因为简单调用中的 this
是 undefined
而不是 window
:
"use strict";
var game = "Football";
function Play() {
console.log(this.game)
}
function PlayGround() {
Play();
}
var obj = new PlayGround();
如果你使用 let
或 const
声明 game
,第二个片段将输出 undefined
因为那些顶部-level 声明不附加到全局范围 window
:
let game = "Football";
function Play() {
console.log(this.game)
}
function PlayGround() {
Play();
}
var obj = new PlayGround();