来自 MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this ,它说:
然而,在严格模式下,this 的值保持在进入执行上下文时设置的值,因此,在以下情况下,this 将默认为 undefined:
function f2() {
'use strict'; // see strict mode
return this;
}
f2() === undefined; // true
这表明如果我 (1) 'use strict'; (2) 在调用 f2 的另一个函数中定义 f2 会为 f2 绑定(bind)外部函数的 this。 但是!
这行不通...
'use strict';
function AlarmClock(clockName) {
this.clockName=clockName;
}
console.log("hello, let's see some weird stuff");
console.log("THIS in global", this);
AlarmClock.prototype.start = function(seconds) {
console.log('outer', this);
var testInside = function() {
console.log('inner', this);
}
testInside();
}
var clock = new AlarmClock("Horizons")
clock.start(1);
// WITHOUT CONSTRUCTORS
function withoutOut() {
console.log("withoutOut", this)
this.howard="notSoBad";
console.log("modifiedTheThis, should have Howard", this)
function withoutIn1() {
console.log("withoutIn1", this);
console.log("Strict should set to the defining object's this");
}
var withoutIn2 = function() {
console.log("withoutIn2", this);
console.log("Strict should set to the defining object's this");
}
withoutIn1();
withoutIn2();
}
withoutOut.bind({Moose: "genius"})();
console.log("DONE");
给出这个输出:
hello, let's see some weird stuff
THIS in global {}
outer AlarmClock { clockName: 'Horizons' }
inner undefined
withoutOut { Moose: 'genius' }
modifiedTheThis, should have Howard { Moose: 'genius', howard: 'notSoBad' }
withoutIn1 undefined
Strict should set to the defining object's this
withoutIn2 undefined
Strict should set to the defining object's this
DONE
注意:我使用 node v10.5.0 从 mac osx 命令行运行了这个。
注意 2:如果你在 devtools 中运行,你必须 follow these steps for use strict.
注意 3:基本上,我想找到一些方法来获得内部,withoutIn1 或 withoutIn2 不被定义。而且,我知道您可以使用显式绑定(bind)来执行此操作,但我想专门获取 MDN 文档中指定的行为。
如果您同意我的看法,MDN 应该将“this”文档更改为只是说,在带有“use strict”的函数上下文中,this 始终设置为未定义。 (作者喜欢)
或者,Chrome 应该更改实现。 (作者不喜欢)
最佳答案
调用函数时 this
的值与函数的定义方式或位置定义完全无关。它只与函数的调用方式有关。调用你的内部函数:
AlarmClock.prototype.start = function(seconds) {
console.log('outer', this);
var testInside = function() {
console.log('inner', this);
}
testInside();
}
像 testInside()
没有任何对象引用意味着没有任何东西可以绑定(bind)到 this
,而在严格模式下这意味着 this
是 未定义
。但是,如果您改写了
testInside.call(this);
然后会有一个上下文值。一个函数在另一个函数“内部”这一事实同样对 this
的绑定(bind)方式完全没有影响。或者:
this.testInside = testInside;
this.testInside();
它也会起作用,因为再一次有一个上下文。
哦,还有,新的(大概)箭头函数机制确实让您创建的函数可以有效地从词法环境中“继承”this
值。所以:
AlarmClock.prototype.start = function(seconds) {
console.log('outer', this);
var testInside = () => {
console.log('inner', this);
}
testInside();
}
会 工作,因为调用箭头函数不涉及任何 this
绑定(bind); this
本质上就像闭包中的变量。
关于javascript - JS : "this" in function context in strict mode, MDN 规范与 chrome 67 实现不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487473/