所以我只是将函数切换为使用箭头函数,现在 this
仅引用我 View 的 Object
。
原始 View
var filterBar = Backbone.View.extend({
initialize: () => {
this.state = {
teams: document.querySelectorAll('[data-team-default]')[0].innerHTML,
comp: document.querySelectorAll('[data-comp-default]')[0].innerHTML,
season: document.querySelectorAll('[data-season-default]')[0].innerHTML,
};
},
el: '.filter-bar',
templates: {
home: require('../../../app/jade/games/index.jade')
},
events: {
'click .filter-bar--filter-button': 'showFilter',
'click .filter-bar--filter-list': 'changeFilter',
},
changeFilter: function (e) {
const currentSelection = e.target.getAttribute('data-url');
return false;
},
showFilter: function (e) {
console.info(this);
e.stopImmediatePropagation();
var t = $(e.currentTarget);
this.closeFilters();
t.siblings('ul').addClass('is-open');
return false;
},
closeFilters: function (e) {
var e = this.$el.find(".is-open");
e.length && e.removeClass("is-open"),
this.$el.hasClass("show-filters") && this.$el.removeClass("show-filters")
}
});
更新 View
var filterBar = Backbone.View.extend({
changeFilter: (e) => {
......
},
showFilter: (e) => {
console.info(this);
......
},
closeFilters: (e) => {
......
}
});
控制台输出:对象{}
为什么现在,this只引用 View 的对象而不是 View 本身。此外,在使用箭头函数时如何让它返回引用 View ?
实际上,我转向箭头函数的原因是访问初始化中设置的 this.state
。
我正在使用 Backbone 版本1.3.3
和Babel 2015
最佳答案
我很困惑为什么你要在这里使用箭头函数。来自 fine manual :
An arrow function expression has a shorter syntax than a function expression and does not bind its own
this
,arguments
,super
, ornew.target
. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
and :
Arrow functions used as methods
As stated previously, arrow function expressions are best suited for non-method functions. [...]
Arrow functions do not define ("bind") their own
this
.
箭头函数的全部要点是拥有一个简短的函数,没有所有面向对象的东西(例如 this
),它们实际上适用于您不关心 的情况>这个
例如:
some_array.map(e => e * 2)
鉴于此:
// (a)
var filterBar = Backbone.View.extend({
initialize: () => {
// (b)
}
});
(b) 处的 this
值与 (a) 处的值完全相同。如果没有大量的组装和体操, View 方法之一中的 this
永远不会是 View 实例(即使如此,甚至可能无法使 initialize
成为箭头函数)。
摘要:不要这样做,这不是箭头函数的用途。
关于javascript - 主干箭头功能和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536327/