javascript - KnockOut 理解 ko.compulated 函数 return 语句中最后一个 "this"引用

标签 javascript knockout.js

我试图理解以下教程示例中最后一个 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()... 表示将此对象内的引用返回到 firstNamelastName 连接到此实例 fullName,我缺少哪一部分?

最佳答案

问题不在于将计算值分配给 this.fullName;它与计算函数内的 this 值有关。默认情况下,在计算函数上下文中计算时,return this.firstName() + ""+ this.lastName(); 中的 thiswindow .

为了解决这个问题,我们通常将 this 捕获到名为 selfthat 的变量中。 ko.compulated() 提供了第二种捕获 this 的方法,即将其作为第二个参数传递。这就是为什么您的代码片段仅在包含第二个 this 参数时才起作用。

请参阅full docs on Computed Observables (向下滚动到管理“此”)了解更多详细信息。

关于javascript - KnockOut 理解 ko.compulated 函数 return 语句中最后一个 "this"引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21787962/

相关文章:

javascript - 改变 ko.observable 的值

javascript - JQuery IF 文档 url = "../products.html"然后执行此操作

javascript - 使用 puppeteer 在页面中基于文本的值搜索中使用正则表达式

javascript - 传单 : how to access and update a marker inside a layer

javascript - Knockout 中当前值的名称

javascript - KnockoutJS fromJS 不工作 TypeError : Cannot call method 'fromJS' of undefined

jquery - 将 KnockoutJs 模板与 jQuery 结合使用

asp.net-mvc - 将 Asp.Net MVC json 结果绑定(bind)到 knockout.js 可观察数组

javascript - 将 xul 对话框置于屏幕中央

javascript - Phonegap 触摸事件处理