【发布时间】:2017-05-04 22:18:42
【问题描述】:
this 在initialize 和render 属性中指的是什么?
JavaScript 代码:
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") });
HTML 代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Backbone.js App</title>
<meta name="description" content="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
</head>
<body>
<div id="search_container"></div>
<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>
<script src="app.js"></script>
</body>
</html>
【问题讨论】:
-
this指的是构造函数
new SearchView创建的实例 -
这是基于What is a view?的教程。
-
最简单的查找方法是
console.log(this),然后查看控制台输出的内容 -
类似的和最近的问题:What is
thisinside a Backbone model? 但答案不是关于上下文的深入。