"this" 在此代码 Backbone 示例中如何运行?

How does "this" function in this code Backbone sample?

this 属性 在此 Backbone.js 代码示例中的功能如何?

由于代码中未指定 use strict 指令并且没有对象传递给任何函数,因此 Backbone.js 代码是默认为全局应用程序对象还是执行其他操作?

我假设 this.render() 可能呈现为通过下划线模板传入的 el 属性 指定的 DOM 元素,但是 this.$el.html?

<script type="text/template" id="search_template">      
  <label>Search</label> 
  <input type="text" id="search_input" /> 
  <input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"> </div>
<script type="text/javascript">
  var SearchView = Backbone.View.extend({ 
      initialize: function({
          this.render(); 
      }, 
      render: function(){ 
          // Compile the template using underscore 
          var template = _.template( $("#search_template").html(), {} ); 
          // Load the compiled HTML into the Backbone "el" 
          this.$el.html( template ); 
      }
  }); 
  var search_view = new SearchView({ el: $("#search_container") }); 
</script>

在此代码示例中,this 是指向 SearchView 的实例视图的指针。

您可以创建该视图的多个实例,并且每个实例都会 this 指向自身。


每个视图实例都有两个指向该视图实例的 DOM 元素的属性。 .el points to the DOM element, and .$el 是指向 DOM 元素的 jQuery 对象。

.$el is that you can call any jquery methods对该对象的好处。

所以 this.$el.html() 意味着您在该视图实例的 DOM 元素上调用 jQuery.html method

在您的代码中,您编译了该视图的模板并将其传递给 $el.html(),后者将模板的 HTML 插入到该视图的 DOM 元素中.


至于initialize中的this.render(),它只是在该实例初始化的那一刻调用该实例的render方法,也就是您看到new 关键字。创建新实例,自动调用initialize方法,调用this.render().

例如,您可以在脚本的最后一行之后直接调用 search_view.render(),而不是在 initialize 中调用 this.render()