[removed] How to avoid addition of a new property in a function?

后端 未结 3 1989
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 03:43

I am a JS newbie, reading a book Javascript Patterns for understanding. One of the code snippets I could see :

var myFunc = function param() {
...
...
};
myFu         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 04:21

    New properties can be added at anytime but it is not necessarily a bad thing. The ability to override implementations is very powerful.

    Normally, you'll want to add methods, objects, etc to the functions prototype, so try

    myFunc.prototype.cache = {};
    

    Ultimately you'll want to follow something like the module pattern

    http://www.yuiblog.com/blog/2007/06/12/module-pattern/

    http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

    Using the module pattern will allow you to create "private" members with privileged access to data via the closures.

提交回复
热议问题