“this”在此代码主干示例中如何工作

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

本文关键字:何工作 工作 this 代码      更新时间:2023-09-26

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指向 DOM 元素,.$el 是指向该 DOM 元素的 jQuery 对象。

.$el的好处是,您可以在该对象上调用任何jquery方法。

因此this.$el.html()这意味着您正在该视图实例的 DOM 元素上调用jQuery.html方法。

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


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

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