Object.defineProperty()
方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
const object1 = {}; Object.defineProperty(object1, 'property1', { value: 42, writable: false }); object1.property1 = 77; // throws an error in strict mode console.log(object1.property1); // expected output: 42
参数:
obj
要定义属性的对象。prop
要定义或修改的属性的名称或 Symbol
。descriptor
要定义或修改的属性描述符。
Object.defineProperty(obj, 'value', { value: 42, writable: false, //value 被改 configurable: false,// 是否可以被删除 enumerable: true, //是否可枚举 get: undefined, // 当访问此属性时,会调用此函数 set: undefined, // 当属性值被修改时,会调用此函数 });
默认值
var o = {}; o.a = 1; // 等同于: Object.defineProperty(o, "a", { value: 1, writable: true, configurable: true, enumerable: true }); // 另一方面, Object.defineProperty(o, "a", { value : 1 }); // 等同于: Object.defineProperty(o, "a", { value: 1, writable: false, configurable: false, enumerable: false });
自定义 setters 和 getters
function Archiver() { var temperature = null; var archive = []; Object.defineProperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getArchive = function() { return archive; }; } var arc = new Archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getArchive(); // [{ val: 11 }, { val: 13 }]
下面这个例子中,getter 总是会返回一个相同的值。
var pattern = { get: function () { return 'I alway return this string,whatever you have assigned'; }, set: function () { this.myname = 'this is my name string'; } }; function TestDefineSetAndGet() { Object.defineProperty(this, 'myproperty', pattern); } var instance = new TestDefineSetAndGet(); instance.myproperty = 'test'; // 'I alway return this string,whatever you have assigned' console.log(instance.myproperty); // 'this is my name string' console.log(instance.myname);
继承属性
通过get和set可以实现 构造函数原型上的属性在所有实例上面共享
function myclass() { } var value; Object.defineProperty(myclass.prototype, "x", { get() { return value; }, set(x) { value = x; } }); var a = new myclass(); var b = new myclass(); a.x = 1; console.log(b.x); // 1
Object.defineProperties() 这个从单词上理解就是 Object.defineProperty()的加强版,可以定义多个
var obj = {}; Object.defineProperties(obj, { 'property1': { value: true, writable: true }, 'property2': { value: 'Hello', writable: false } // etc. etc. });