如何在backbone.js模型中添加私有函数?

19 javascript backbone.js

有没有办法在骨干网中创建一个私有函数,以便它只暴露给模型本身并且还可以访问this

我该如何updateTime私密?

   var Timeline = Backbone.Model.extend({
        url: 'servertime/',

        start: function(){
            this.fetch({
                success: function(timeline, response){
                    timeline.updateTime();
                    setInterval(function() {
                        timeline.updateTime();
                    }, 60 * 1000);
                }
            });
        },

        updateTime: function(){  //How can I make this private?
            this.time = ...
        }
    });
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 14

你可以通过将它全部包装在一个自动调用的匿名函数中来实现这一点,这样你就可以确保updateTime是私有的:

(function() {
  var updateTime = function(){  // this stays private to this anonymous function
    this.time = ...
  },
  Timeline = Backbone.Model.extend({
    url: 'servertime/',

    start: function(){
      this.fetch({
        success: function(timeline, response){
          updateTime.call(timeline);
          setInterval(function() {
            updateTime.call(timeline);
          }, 60 * 1000);
        }
      });
    }
  });

})();
Run Code Online (Sandbox Code Playgroud)


mas*_*lum 7

你可以做updateTime一个私人的功能,但不是私人的方法.我还建议在前置下划线以明确它是一个私有函数.

(function() {
  function _updateTime(timeline){
    timeline.time = ...
  }

  Timeline = Backbone.Model.extend({
    url: 'servertime/',

    start: function(){
      this.fetch({
        success: function(timeline, response){
          _updateTime(timeline);
          setInterval(function() {
            _updateTime(timeline);
          }, 60 * 1000);
        }
      });
    }
  });

})();
Run Code Online (Sandbox Code Playgroud)

  • @GeorgeJempty:我不同意.按惯例为带下划线的方法添加前缀表明它是私有的,即使它是可公开访问的.我在JS设计模式书中读到过这个. (2认同)