chuanxshi / javascript-patterns

JavaScript Design Patterns

Home Page:http://shichuan.github.io/javascript-patterns

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use `hasOwnProperty` in the memoization pattern

mathiasbynens opened this issue · comments

  var myFunc = function (param) {
    if (!myFunc.cache[param]) {
      var result = {};
      // ... expsensive operation ...
      myFunc.cache[param] = result;
    }
    return myFunc.cache[param];
  };

If param is e.g. "toString" this will cause problems.

({})['toString'] // function toString() { [native code] }

The solution is to use hasOwnProperty.

@mathiasbynens thanx for pointing this out, will use the existing one as an antipattern and put up one with hasOwnProperty as the preferred way.

Preferred method 3 seems to have the same problem, isn't it?

Yes it looks like it does, plus arguments.callee is deprecated (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)