gpt4 book ai didi

javascript - Reactjs:在JavaScript中,默认不绑定(bind)类方法

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:59 29 4
gpt4 key购买 nike

我正在关注 handling-events documentation ,我遇到了这个:

In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

我从这段引文中了解到,this 并未指定每个类方法中的当前实例化。

但是,如果我考虑下面的代码,方法 editState 可以通过 访问扩展类 Parent 的属性 state这个。这会使前面的引述错误,因为 this 绑定(bind)到所有类方法。

class Parent {
constructor() {
this.state = false;
}

setState(newState) {
this.state = newState;
}
}

class Child extends Parent {
editState() {
this.setState(true);
}
}

let c = new Child;
c.editState();
console.log(c.state);

我在这里错过了什么?

最佳答案

当函数用作事件处理程序时,其“this”设置为触发事件的元素。 As a DOM event handler

关于javascript - Reactjs:在JavaScript中,默认不绑定(bind)类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46275742/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com