javascript - `this` 在使用 bind() call() 或 apply() 时未传递给函数

标签 javascript

<分区>

我正在使用 React,在我的 componentDidMount() {} 中我正在调用一个导入的函数,并想在其中访问 this.setState

componentDidMount 中,当我 console.log(this) 时,我按预期获得了组件。

但是如果我运行 myFunction.call(this),myFunction 中的 console.log(this) 将返回 undefined

知道为什么 this 没有被正确传递吗?

edit1:添加代码。

组件:

class Navbar extends React.Component {
    componentDidMount() {
        myFunction.call();
    }
}

我的函数.js:

export const myFunction = () => {
    console.log('this:', this);
}

控制台输出:

this: undefined

edit2:有些人将其标记为“我可以绑定(bind)箭头函数”的副本,但 myFunction 是一个箭头函数,即使我直接调用它而不是使用 .call() 也会产生相同的结果:this 未定义。

最佳答案

在构造函数中绑定(bind)导入函数:

import { myFunction } from './path/to/myFunction';

class Navbar extends React.Component {
    constructor() {
       /* other constrcutor code */
       myFunction = myFunction.bind(this);
    }
    componentDidMount() {
       myFunction();
    }
}

在您的 myFunction.js 中,将 ES6 箭头函数转换为常规 ES5 函数(参见 Can you bind arrow functions? ):

export const myFunction = function() {
    console.log('this:', this);
}

关于javascript - `this` 在使用 bind() call() 或 apply() 时未传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672691/

相关文章:

javascript - .NET webclient 向 Javascript 请求代码

javascript - Meteor 应用程序构建奇怪的文件;没有js/css资源

javascript - 将数组成员设置为 null 而不是 ""

javascript - 在 Json 对象中搜索元素

javascript - 将值设置为 aria-controls 输入

javascript - 大型 jquery 数据表使用 django 很慢

javascript - Jquery 获取选择器

javascript - 使用 CryptoJS 加密并使用 PHP 解密

javascript - 实例化和填充对象数组的更快方法

javascript - d3 缩放基本形状