我是js新人,这是knockout.js里的一個示例
html
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
Js
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function(){
return this.firstName() + " " + this.lastName();
},this);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
我有点不太理解fullName里function最后的this是什么作用,function的参数?还是别的?
它指向的是谁?该怎么可以透彻的理解这个语句?
我经常对匿名function(){}后面直接加参数这种行为理解不能,有没有什么好的文章介绍相关的内容?
谢谢大家
关于
this
,我已经在JavaScript 的 this 指向问题深度解析 进行了详细的讲述,所以这里就不重复了。具体到这个问题,是关于
ko.computed()
的 API,看看从官方文档摘取的一段:大致翻译一下第一句就是:
ko.computed
的第二个参数指定在执行 computed 观察函数时的this
。所以在
ko.computed(function() {...}, this)
这里传入的this
,就是在function() {...}
使用的this
,即this.firstName()
和this.secondName()
的那个this
。也就是AppViewModel
作用域中的this
。