新 object 实例复制方法具有未定义的上下文。 (对不起误导的标题)
New object instance copy method has undefined context. (sorry for misleading title)
我很好奇为什么这个 ES6 代码输出 undefined
:
class Test {
constructor(name) {
this.name = name;
}
log() {
console.log(this);
}
}
const t = new Test('asd');
const asd = t.log;
asd();
但是这个 ES5 代码输出 window
.
function Test(name) {
this.name = name;
}
Test.prototype.log = function() {
console.log(this)
}
const t = new Test('newer test');
const asd = t.log;
asd();
从技术上讲,在 globar 分数中调用了某些东西,它前面有 window.thatSomething,但显然如果 thatSomething 是 class,则没有 window。
这是因为 class
默认情况下使您的代码使用 strict mode. Normally, the value of this
will be assigned to the global object (window
) if not determined 但在严格模式下,它被设置为 undefined
以防止意外问题,例如使用全局对象的属性:
function sayName() {
console.log("Hello, my name is " + this.name + "!");
}
function sayNameStrict() {
"use strict";
console.log("Hello, my name is " + this.name + "!");
}
let obj = {
name: "Fred",
sayName: sayName,
sayNameStrict: sayNameStrict
}
obj.sayName(); //this = obj, this.name = "Fred
sayName(); //this = window, this.name = window.name
obj.sayNameStrict(); //this = obj, this.name = "Fred
sayNameStrict(); //this = undefined, this.name = TypeError
因此,如果您在严格模式下执行第二段代码,您将获得与 ES6 相同的结果 class:
"use strict";
function Test(name) {
this.name = name;
}
Test.prototype.log = function() {
console.log(this)
}
const t = new Test('newer test');
const asd = t.log;
asd();
我很好奇为什么这个 ES6 代码输出 undefined
:
class Test {
constructor(name) {
this.name = name;
}
log() {
console.log(this);
}
}
const t = new Test('asd');
const asd = t.log;
asd();
但是这个 ES5 代码输出 window
.
function Test(name) {
this.name = name;
}
Test.prototype.log = function() {
console.log(this)
}
const t = new Test('newer test');
const asd = t.log;
asd();
从技术上讲,在 globar 分数中调用了某些东西,它前面有 window.thatSomething,但显然如果 thatSomething 是 class,则没有 window。
这是因为 class
默认情况下使您的代码使用 strict mode. Normally, the value of this
will be assigned to the global object (window
) if not determined 但在严格模式下,它被设置为 undefined
以防止意外问题,例如使用全局对象的属性:
function sayName() {
console.log("Hello, my name is " + this.name + "!");
}
function sayNameStrict() {
"use strict";
console.log("Hello, my name is " + this.name + "!");
}
let obj = {
name: "Fred",
sayName: sayName,
sayNameStrict: sayNameStrict
}
obj.sayName(); //this = obj, this.name = "Fred
sayName(); //this = window, this.name = window.name
obj.sayNameStrict(); //this = obj, this.name = "Fred
sayNameStrict(); //this = undefined, this.name = TypeError
因此,如果您在严格模式下执行第二段代码,您将获得与 ES6 相同的结果 class:
"use strict";
function Test(name) {
this.name = name;
}
Test.prototype.log = function() {
console.log(this)
}
const t = new Test('newer test');
const asd = t.log;
asd();