Javascript:如何避免在函数中添加新属性? [英] Javascript : How to avoid addition of a new property in a function?
问题描述
我是JS新手,正在阅读 JavaScript模式以便理解.我可以看到的代码片段之一:
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.
谢谢!
推荐答案
JavaScript从未真正有任何选项来保护对象,但是从ECMAScript 5开始,您现在可以
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
}
这篇关于Javascript:如何避免在函数中添加新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!