微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在JavaScript中将类方法分离为单独的模块

如何解决在JavaScript中将类方法分离为单独的模块

我有一个方法'joinRoom',它是使用fat aero创建的,所以我认为我不需要传递'this'作为参数或绑定它。这很明显,但是我想将joinRoom函数存储在另一个文件中,但是该文件(用于模块化方法并保持我的此文件干净)包含'this'关键字。如何处理该模块中的“ this”关键字?检查下面的代码

main.js

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
        }
        this.socket = null
    }
    joinRoom = () => joinRoom() //this one
    render() {
        return();
    }
}

whoisOnline.js

whoisOnline = () => {
    sendToPeer('onlinePeers',null,{local: this.socketID})
}

我只想将所有方法保留在该类的另一个模块中,但是它们都涉及'this'关键字,如何处理这种情况,请事先告知我。

解决方法

我只是试图找到一条出路,我必须将'this'作为参数传递,以便该对象在函数中可用,然后在函数中可以使用它。

main.js

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
        }
        this.socket = null
    }
    joinRoom = () => joinRoom(this) //passed 'this' keyword 
    render() {
        return();
    }
}

whoisOnline.js

whoisOnline = (object) => { // passed object argument and then used it to access 'this' from the calss
    sendToPeer('onlinePeers',null,{local: object.socketID})
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。