我有一个具有多个实例的类,每个实例都有一个或两个该实例唯一的方法。我希望能够使用构造函数实例化这些方法,但通常这些方法还将依赖于另一个值,也在构造函数中实例化,该值可能稍后在运行时更改(例如
name
和 text
稍后会更改,并且我希望 foo
使用最新的值)。这是一个简单的简单示例(使用 React 语法,因为这就是我正在使用的):
export default function Home() {
class Test {
constructor(name, text, foo){
this.name = name;
this.text = text;
this.foo = foo;
}
}
const test1 = new Test("Test 1", "I am a test", () => {console.log(this.name)})
const test2 = new Test("Test 2", "I am also a test", () => {console.log(this.text)})
return(
<>
<button onClick={test1.foo}>{test1.name}</button>
<button onClick={test2.foo}>{test2.name}</button>
</>
)
}
单击任一按钮时,都会抛出一个错误,指出
this
未定义,我可以理解,因为它在创建时不存在。我可能可以添加第二个函数,在创建实例后将方法分配给 foo
,但我希望创建许多实例,并且我宁愿一次性完成所有操作。有什么方法可以在构造函数属性中使用 this
或获得类似的效果吗?
箭头函数使用外部作用域中的
this
,只需更改为普通函数,因此调用上下文将作为 this
传递给函数:
将
() => {console.log(this.name)}
更改为function () {console.log(this.name)}
:
export default function Home() {
class Test {
constructor(name, text, foo){
this.name = name;
this.text = text;
this.foo = foo;
}
}
const test1 = new Test("Test 1", "I am a test", function () {console.log(this.name)})
const test2 = new Test("Test 2", "I am also a test", function () {console.log(this.text)})
return(
<>
<button onClick={test1.foo}>{test1.name}</button>
<button onClick={test2.foo}>{test2.name}</button>
</>
)
}
您可以完全避免上课的替代方案:
export default function Home() {
const test1 = {name: "Test 1", text: "I am a test", foo() {console.log(this.name)}};
const test2 = {name: "Test 2", text: "I am also a test", foo() {console.log(this.text)}};
return(
<>
<button onClick={test1.foo}>{test1.name}</button>
<button onClick={test2.foo}>{test2.name}</button>
</>
)
}