简体   繁体   中英

Data context for computed observable function in Knockout.js

I am comparing two ways of using computed observable function in Knockout.js

Question:

  1. Can "this" keyword in function refers to it's parent object (outside, not function inside)?
  2. Why version 2 works even without putting the context value at the end ?

      ///Version 1 my.Product = function () { this.id = ko.observable(); this.salePrice = ko.observable(); this.photo = ko.observable(); this.shortDescription = ko.observable(); this.photoUrl = ko.computed (function () { return photoPath + this.photo(); },this); //**context** }; ////version 2 my.Product = function () { var self = this; self.id = ko.observable(); self.salePrice = ko.observable(); self.photo = ko.observable(); self.shortDescription = ko.observable(); self.photoUrl = ko.computed(function () { return photoPath + self.photo(); });//why there is no "self" here }; 

I am not sure I understand your 1st question. In the first case, you're passing "this" to be able to refer to "this" as "this" in your computed function. It is specific to knockout, but knockout probably uses call or apply . Both allow to redefine "this". If you did not pass "this" as the second parameter "this" would refer to the computed function scope. And this.photo would be undefined.

The second case is a common javascript "trick". It consists in assigning "this" to a variable to be able to refer to it in another scope. You do not have to pass "self" as a parameter because it is a variable and it is accessible from the function.

Both examples are valid. I personally prefer the second one because it is a more usual way of dealing with javascript execution contexts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM