bind和var self之间的差异=this
Difference between bind and var self=this?
在我的react本机代码中,我在模块的多个位置同时使用bind(this)
和var self = this;
。
两者都在正确的位置解决了this
关键字的解析问题。
以下是我的代码(执行相同功能的2个代码)-
-
使用
bind(this)
retval.then(function (argument) { console.log("argument"+JSON.stringify(argument)); this.stateSetting(argument); }.bind(this));
-
使用
var self = 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
。它更结构化,更接近于函数方法,这使得代码更容易推理,就像你通过使用promise发现的那样。它似乎也更具表演性。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 函数中this和var之间的区别
- 同一元素的 this.id 值在浏览器之间是不同的
- 使用变量self与this之间的区别
- $(this.el).html 和 this.$el.html 之间有什么区别
- jquery中的(this)和(_this)之间有什么区别吗?
- 函数(){}.bind(this) 和 angular.bind(this, function() {}) 之间的区别
- this.form 和 document.forms 之间的区别
- 在 JavaScript 中,在声明对象的新键:值对时,引用对象的变量名与使用“this”之间是否存在差异
- this.function 和 this.function() 之间的区别
- 客户端与服务器端 JavaScript 中“this”的值之间的差异
- JavaScript:继承时this.watever和prototype.whatever之间的区别
- this.key和this[key]之间的差异,使用angularjs for Each
- bind和var self之间的差异=this
- jquery中每个循环中的$(this)和$(“#id”)之间的差异
- casper.then()和this.then()之间的区别
- $(this)之间的差.和document.getElementById().src
- $this之间的区别.Text和$this.值以及为什么1返回空值
- Javascript -这两者之间有区别吗?Foo和this.prototype.foo
- $(“select”)和$(“selection”,$(this))之间的区别是什么