简而言之,我正在尝试在window
中定义一个变量,该变量与类中的myValue
保持同步。因此,window.myGlobalVarName
应该始终等于类中的myValue
。
我正在使用Object.defineProperty
来尝试防止变量在window
中重新分配。
但是,无论何时调用get()
,this
都是window
对象,而不是类中的this
对象。 我在这里错过了一些明显的东西吗?有很多使用get()
在类中使用this
返回值的示例 - 我做了什么不同的事情?
class MyClass {
constructor() {
this.myValue = 1
this.globalVarName = "myGlobalVarName"
this.setGlobalObject()
}
setGlobalObject() {
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get() { return this.myValue } // "this" is actually "window"
})
}
}
}
我可以解决这个问题,返回函数的值,但我能用更好的方法做到这一点吗?
setGlobalObject() {
const getMyValue = () => this.myValue // Return current value of this.myValue
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get() { return getMyValue() } // Returns the actual value from the class
})
}
}
但是,无论何时调用
get()
,this
都是窗口对象,而不是类中的this
对象。
这就是大多数函数和方法在 JavaScript 中的工作方式,this
是由它们的调用方式设置的,而不是定义它们的位置。此问题的答案中的详细信息。您的get
函数是相同的,因为它是传统函数(使用方法语法编写(。
若要从定义函数的位置获取this
,请使用箭头函数:
class MyClass {
constructor() {
this.myValue = 1
this.globalVarName = "myGlobalVarName"
this.setGlobalObject()
}
setGlobalObject() {
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get: () => this.myValue // ***
})
}
}
}
箭头函数没有自己的this
,它们在定义它们的范围内关闭this
,就像它们是它们关闭的变量一样。上面的setGlobalObject
与ES2015之前的函数基本相同:
// Pre-ES2015 example for comparison
MyClass.prototype.setGlobalObject = function setGlobalObject() {
var obj = this; // ***
if (typeof window !== "undefined") {
Object.defineProperty(window, this.globalVarName, {
configurable: false,
enumerable: true,
get: function() { return obj.myValue; } // ***
})
}
};
(箭头函数也没有自己的arguments
对象、new.target
或super
。