本文介绍了避免将方法和属性添加到自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用扩展了原型的基本自定义对象

I'm using a base custom object extended with prototype

function Person() {}

Person.prototype.Name      = "";
Person.prototype.Lastname  = "";

var NewPerson= new Person();

NewPerson.Name      = "Nancy";
NewPerson.Lastname  = "Drew";   //<--- right way

NewPerson.lastname  = "Drew";   //<--- wrong property

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

I need to avoid to add new properties and methods in a defined object because it would generate silent errors and bugs.

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

I know that javascript has a terrible way to manage classes/objects, but there's a way to protect it?

我发现 冻结 密封 ,但那些阻止我更改值。

I found freeze and seal but those prevent me from changing the values.

推荐答案

可以使用Object.seal更改值

Values can be changed with Object.seal

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

The Object.seal() method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.

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"}

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

If you desire to actually freeze the prototype of the object while leaving other parts writable then you can try this approach

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

这篇关于避免将方法和属性添加到自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:41