What “this.data = this.data || {}” means in Memoization pattern?

≯℡__Kan透↙ 提交于 2020-06-01 02:29:22

问题


I am a student studying javascript, and I encountered a problem while studying memoization pattern. This is the code :

Function.prototype.memoization = function(key) {
   var arg = Array.prorotype.slice.call( arguments, 1 );
   this.data = this.data || {} ;    //THE code

   return this.data[key] !== undefined ?
       this.data[key] : this.data[key] = this.apply(this, arg);
};

For me it is shown as just OR operation between an array and a blank array, and I cannot understand why such code is needed.


回答1:


The || operator in JavaScript can also be used for conditional evaluation since it "short circuits". If the left hand side of the operator evaluates to true, there's no need to check the right hand side.

The interpreter evaluates the left-hand side of the operator and returns the result if it evaluates to something different than false or null, otherwise the right hand side is evaluated and returned.

let x = 1 || 2;
// Prints 1
print(x);

let y = null || 3;
// Prints 3
print(y);

In your example: if there's something in this.data then that same information will be stored in this.data, otherwise an empty object is assigned.




回答2:


This makes sure this.data has a value if it's not defined. When this.data is undefined or null the this.data || {} expression becomes undefined || {} (or null || {}) which evaluates to {}




回答3:


It is for setting default value. If a given object has no value assigned to key data, this.data returns undefined value. undefined value is proned to result unexpected behaviors and errors. So we need to set default value for data. In this case it is an empty object {}. If you are familiar with PHP(v 7.0 or higher), it is similar to ?? notation.



来源:https://stackoverflow.com/questions/58333984/what-this-data-this-data-means-in-memoization-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!