Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript bind和var self之间的差异=这个?_Javascript_Reactjs_This_Bind_React Native - Fatal编程技术网

Javascript bind和var self之间的差异=这个?

Javascript bind和var self之间的差异=这个?,javascript,reactjs,this,bind,react-native,Javascript,Reactjs,This,Bind,React Native,在我的react原生代码中,我同时使用bind(this)和var self=this在模块的多个位置 两者都解决了在正确的位置解析这个关键字的问题 以下是我的代码(执行相同功能的两个代码)- 使用bind(this) 使用var self=this retval.then(function (argument) { console.log("argument"+JSON.stringify(argument)); this.stateSetting(argument); }.

在我的react原生代码中,我同时使用
bind(this)
var self=this在模块的多个位置

两者都解决了在正确的位置解析
这个
关键字的问题

以下是我的代码(执行相同功能的两个代码)-

  • 使用
    bind(this)

  • 使用
    var self=this

    retval.then(function (argument) {
        console.log("argument"+JSON.stringify(argument));
        this.stateSetting(argument);
    }.bind(this));
    
    var self = this;
    retval.then(function (argument) {
       console.log("argument"+JSON.stringify(argument));
       self.stateSetting(argument);
    });
    

  • 考虑到他们都做同样的工作,我很想知道什么是正确的方式来做这件事?使用其中一个有问题吗?或者有更好的方法吗?

    鉴于您的目标是实现ES2015的Node.js,您最好使用箭头函数。 箭头函数具有所谓的
    this
    ,这意味着箭头函数中的变量
    this
    被视为正常变量,并且在创建函数时将被视为正常变量

    因此,您的代码变成:

    retval.then((argument) => {
        console.log("argument"+JSON.stringify(argument));
        // "this" will inherit the value of the outside scope
        this.stateSetting(argument); 
    });
    

    如果针对ES5(旧浏览器),那么我更喜欢
    .bind
    样式,而不是
    var self=this
    。它更结构化,更接近于函数式方法,这使得代码更容易推理,就像您通过使用承诺所发现的那样。似乎也是这样。

    两者都很好。我会尝试在应用程序或至少是模块中保持某种程度的一致性。ES6箭头函数是一种更好的方法。感谢Robert:)我只是想知道,如果我执行类似于
    if(self==this)
    的操作,则返回true。那么,有没有办法摧毁自我?如果它是一个对象,我可以做-
    self={}
    。在这种情况下,我应该将self指向null吗?@Oriol是的,我肯定会使用ES6箭头函数。你能给我一个比苏多代码吗?我在很多其他地方使用了arrow函数。很简单:
    retval.then((参数)=>{console.log(“参数”+JSON.stringify(参数));this.stateSetting(参数);})