繁体   English   中英

从视图内部调用方法而不使用“ this”关键字?

[英]Calling a method from inside a view without using “this” keyword?

我的主干代码似乎有很多this.methodCall()类型的调用,我很希望能够删除this ,而直接从View内部调用methodCall()

请参见以下代码:

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()具有截然不同的含义。

实现调用方式setPageCookies()没有this将是使setPageCookies函数声明:

function setPageCookies() {

}

Backbone.View.extend({ 
  setPageCookies: setPageCookies,
  initialize: function() {
    setPageCookies()
  }
});

但是,现在不能用this代替setPageCookies除非使用bind ,或者除非围绕setPageCookies: setPageCookies编写了一个复杂的包装器setPageCookies: setPageCookies ,它使用this值并将其作为第一个参数传递。 这让我问-为什么要实现这一目标?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM