[英]KnockOut understanding ko.computed function last “this” reference in return statement
I am trying to understand what the use of the last this
in the following tutorial example 我想了解什么用最后的
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!
}
I understand that the other this
's pertain to the AppViewModel()
being constructed and when I remove the comma and last this
the example doesn't bind any data. 据我所知,其他
this
的属于该AppViewModel()
被构造和当我删除逗号和持续this
示例中不结合的任何数据。 With the this.fullName
wouldn't that be sufficient to bind that function to the AppViewModel()
? 使用
this.fullName
不足以将该函数绑定到AppViewModel()
?
So as it stands the ko.computed(function()...
is saying return the references within this object to firstName
and lastName
concatenated set to this instances fullName
, what piece am I missing? 因此,它代表
ko.computed(function()...
表示将此对象中的引用返回给firstName
和lastName
连接设置为此实例fullName
,我错过了什么?
The problem isn't the assignment of the computed to this.fullName
; 问题不在于将
this.fullName
赋值给this.fullName
; it has to do with the value of this
inside the computed function. 它与价值做
this
计算函数内。 By default, the this
in return this.firstName() + " " + this.lastName();
默认情况下,
this
return this.firstName() + " " + this.lastName();
when evaluated in the context of the computed function is window
. 当在计算函数的上下文中计算时是
window
。
To get around this, we typically capture this
into a variable called self
or that
. 为了解决这个问题,我们通常捕捉
this
到一个变量称为self
或that
。 ko.computed()
provides a second way to capture this
, and that's by passing it in as the second parameter. ko.computed()
提供到捕获第二方式this
,这是通过在将它作为第二个参数。 That is why your snippet will only work when you include the second this
parameter. 这就是为什么您的代码段仅在包含第二个
this
参数时才起作用的原因。
See the full docs on Computed Observables (scroll down to Managing "this") for more details. 有关详细信息,请参阅Computed Observables的完整文档 (向下滚动到“管理”这个“)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.