我试图理解以下教程示例中最后一个 this
的用途
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function(){
return this.firstName() + " " + this.lastName();
},this);//This one!
}
据我了解,另一个 this
与正在构造的 AppViewModel()
相关,当我删除逗号和最后一个 this
时,示例不绑定(bind)任何数据。使用 this.fullName
是否足以将该函数绑定(bind)到 AppViewModel()
?
就目前情况而言,ko.compulated(function()...
表示将此对象内的引用返回到 firstName
和 lastName
连接到此实例 fullName
,我缺少哪一部分?
最佳答案
问题不在于将计算值分配给 this.fullName
;它与计算函数内的 this
值有关。默认情况下,在计算函数上下文中计算时,return this.firstName() + ""+ this.lastName();
中的 this
为 window
.
为了解决这个问题,我们通常将 this
捕获到名为 self
或 that
的变量中。 ko.compulated()
提供了第二种捕获 this
的方法,即将其作为第二个参数传递。这就是为什么您的代码片段仅在包含第二个 this
参数时才起作用。
请参阅full docs on Computed Observables (向下滚动到管理“此”)了解更多详细信息。
关于javascript - KnockOut 理解 ko.compulated 函数 return 语句中最后一个 "this"引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21787962/