避免向自定义对象添加方法和属性

时间:2015-06-08 12:28:35

标签: javascript ecmascript-5

我正在使用扩展了原型

的基本自定义对象
$this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0',false);
$this->output->set_header('Pragma: no-cache');

我需要避免在已定义的对象中添加 new 属性和方法,因为它会生成无提示错误和错误。

我知道javascript有一种管理类/对象的可怕方法,但有一种方法可以保护它吗?

我发现 冻结 封印 ,但这些阻止我更改值。

1 个答案:

答案 0 :(得分:1)

  

我发现了冻结和封印,但那些阻止我改变价值观。

可以使用Object.seal

更改值

Object.seal()方法密封对象,防止将新属性添加到对象中,并将所有现有属性标记为不可配置。 当前属性的值仍然可以更改,只要它们是可写的。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal

http://plnkr.co/edit/Wut7lsOxdFuz2VzsFzCM?p=preview

function Person(){
  this.name = "";
  this.id = "";
  Object.seal(this);
}

var p1 = new Person();

p1.name = "Mike";
p1.id = "A1";
p1.age = 32;

console.log(p1); //Person {name: "Mike", id: "A1"}

如果您希望实际冻结对象的原型,同时保留其他部分可写,那么您可以尝试这种方法

function Person(){
  this.name = "";
  this.id = "";
  Object.seal(this);
}

//this will add to Person
Person.prototype.test = function(){
  alert("hi");
}

Object.freeze(Person.prototype);

//this won't
Person.prototype.test2 = function(){
  alert("hi");
}

var p1 = new Person();


p1.name = "Mike";
p1.id = "A1";
p1.age = 32;

console.log(p1); //Person {name: "Mike", id: "A1"} test will be on the proto