Javascript 访问';这';iffe中的语境
假设我有一个带有方法foo()的javascript类。在另一个方法f.e componentDidMount中,我想访问iffe中的方法foo()。如何将“this”上下文绑定到iffe中 我知道我可以使用this=self并使用它,或者使用arrow语法,但是我想扩展我对js&this的知识,并因此使用适当的绑定来完成它。我试过:Javascript 访问';这';iffe中的语境,javascript,reactjs,Javascript,Reactjs,假设我有一个带有方法foo()的javascript类。在另一个方法f.e componentDidMount中,我想访问iffe中的方法foo()。如何将“this”上下文绑定到iffe中 我知道我可以使用this=self并使用它,或者使用arrow语法,但是我想扩展我对js&this的知识,并因此使用适当的绑定来完成它。我试过: (function doSomething() { this.foo(); }.bind(this)()) 但这不起作用。示例代码: class Test
(function doSomething() {
this.foo();
}.bind(this)())
但这不起作用。示例代码:
class Test extends React.Component {
constructor(props) {}
public componentDidMount() {
(function doSomething() {
this.foo();
})();
}
foo() {
// ...
}
}
iife的常见模式是使用函数参数
class Test extends React.Component {
constructor(props) {}
public componentDidMount() {
(function doSomething(self) {
self.foo();
})(this);
}
foo() {
// ...
}
}
如果不能或不想使用箭头函数,可以手动将函数绑定到外部上下文:
(function doSomething() {
this.foo();
}.bind(this))();
javascript中
这个
关键字背后的逻辑将在这个问题中详细讨论:或者在凯尔·辛普森(Kyle Simpson)的这本神奇的书中:@Seblor请阅读这个问题。“我知道我可以使用arrow语法,但我想扩展我对js的了解&这一点,并因此使用适当的绑定来实现。”…该死,你说得对。Tslint抱怨是这里的问题,而不是实际的代码。很抱歉