在不使用 "this" 关键字的情况下从视图内部调用方法?
Calling a method from inside a view without using "this" keyword?
我的 backbone 代码似乎有大量 this.methodCall()
类型的调用,我希望能够删除 this
,只调用 [=14] =] 直接从视图内部。
参见下面的代码:
app.Main = Backbone.View.extend({
el: '#main-div',
// how do I call this function without invoking "this"?
setPageCookies: function () {
console.log('setting page cookies called!');
},
initialize: function () {
// saw this online as a possible solution, but only seems to affect the scope of "this"
_.bindAll(this, 'setPageCookies');
// this works:
this.setPageCookies();
// HOWEVER, I'd like to be able to call it like this instead:
setPageCookies();
}
});
首先 - this.setPageCookies()
和 setPageCookies()
具有截然不同的含义。
在没有 this
的情况下实现调用 setPageCookies()
的方法是使 setPageCookies
成为一个函数声明:
function setPageCookies() {
}
Backbone.View.extend({
setPageCookies: setPageCookies,
initialize: function() {
setPageCookies()
}
});
但是,现在您不能使用 this
而不是 setPageCookies
- 除非您使用 bind
,或者除非您围绕 setPageCookies: setPageCookies
编写复杂的包装器this
值并将其作为第一个参数传递.. 或其他。这让我问 - 你为什么要实现这一目标?
我的 backbone 代码似乎有大量 this.methodCall()
类型的调用,我希望能够删除 this
,只调用 [=14] =] 直接从视图内部。
参见下面的代码:
app.Main = Backbone.View.extend({
el: '#main-div',
// how do I call this function without invoking "this"?
setPageCookies: function () {
console.log('setting page cookies called!');
},
initialize: function () {
// saw this online as a possible solution, but only seems to affect the scope of "this"
_.bindAll(this, 'setPageCookies');
// this works:
this.setPageCookies();
// HOWEVER, I'd like to be able to call it like this instead:
setPageCookies();
}
});
首先 - this.setPageCookies()
和 setPageCookies()
具有截然不同的含义。
在没有 this
的情况下实现调用 setPageCookies()
的方法是使 setPageCookies
成为一个函数声明:
function setPageCookies() {
}
Backbone.View.extend({
setPageCookies: setPageCookies,
initialize: function() {
setPageCookies()
}
});
但是,现在您不能使用 this
而不是 setPageCookies
- 除非您使用 bind
,或者除非您围绕 setPageCookies: setPageCookies
编写复杂的包装器this
值并将其作为第一个参数传递.. 或其他。这让我问 - 你为什么要实现这一目标?