[removed] How to avoid addition of a new property

2019-02-24 08:51发布

问题:

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

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

This indicates a new property can be added by anyone outside the function body. Doesn't this break encapsulation ? What if some other part of program keeps on adding new properties making my object creation bulky ? What if someone deletes/modifies properties defined by me ?

I don't know if I am right in calling this a "problem". But if it is, please help with an approach to avoid this.

Thanks !

回答1:

JavaScript never really had any options to secure your objects but starting in ECMAScript 5 you can now freeze an object.

var o = { a: 1, b: 2 };
Object.freeze(o);
console.log(o.a); // 1
o.a = 2;
console.log(o.a); // 1

There is also a new context known as strict mode where an error can be thrown.

function processObject(o) {
    "use strict";
    delete o.a; // throws a TypeError
}


回答2:

Doesn't this break encapsulation ?

Yes and no. If you use a closure, you can still have "private" variables in the sense that they cannot be accessed from outside of the object's functions as declared at instantiation time. Example:

var ObjectPrototype = function () {
   var privateVariable = "closure-scope value";
   var InnerPrototype = function () {
       this.getPrivate = function () { return privateVariable; };
   };
   return new InnerPrototype();
};
var myObject = new ObjectPrototype();

Because the ObjectPrototype returns a new instance of the InnerPrototype, and privateVariable exists only within the ObjectPrototype closure, there is no way to access privateVariable directly from the outside. The only way to get the value of it is through myObject.getPrivate().

Note: Javascript passes objects and arrays by reference, so this method only truly protects simple values (unless you are careful to return clones instead).

What if some other part of program keeps on adding new properties making my object creation bulky ?

That is something that you'll just need to keep an eye on.

What if someone deletes/modifies properties defined by me ?

Use the closure-scoping method I described above to prevent this.



回答3:

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.