定义属性
需要三个参数
obj 要定义属性的那个对象
prop 要定义的属性名
descriptor 描述项集合 配置集合
案例
function defineProperty() {
var _obj = {};
Object.defineProperty(_obj, 'a', {
value: 1,
});
return _obj;
}
var obj = defineProperty();
console.log(obj);
defineProperties一次定义多个属性
function defineProperty() {
var _obj = {};
Object.defineProperties(_obj, {
a: {
value: 1,
},
b: {
value: 2,
},
});
return _obj;
}
var obj = defineProperty();
console.log(obj);
obj.a = 5;
console.log(obj);
for (var k in obj) {
console.log(k + ': ' + obj[k]);
}
delete obj.a
因为writable默认为false 不可写
改为true后
function defineProperty() {
var _obj = {};
Object.defineProperties(_obj, {
a: {
value: 1,
writable: true,
},
b: {
value: 2,
},
});
return _obj;
}
var obj = defineProperty();
obj.a = 5;
obj.b = 6;
console.log(obj);
enumerable 是否是可枚举的 默认为false
改为true后
function defineProperty() {
var _obj = {};
Object.defineProperties(_obj, {
a: {
value: 1,
writable: true,
enumerable: true,
},
b: {
value: 2,
},
});
return _obj;
}
var obj = defineProperty();
obj.a = 5;
obj.b = 6;
console.log(obj);
for (var key in obj) {
console.log(key + ':' + obj[key]);
}
configurable 是否是可配置的 可操作的 默认为false
当设置为true后
function defineProperty() {
var _obj = {};
Object.defineProperties(_obj, {
a: {
value: 1,
writable: true,
enumerable: true,
configurable: true,
},
b: {
value: 2,
},
});
return _obj;
}
var obj = defineProperty();
obj.a = 5;
obj.b = 6;
console.log(obj);
for (var key in obj) {
console.log(key + ':' + obj[key]);
}
delete obj.a;
每一个属性定义的时候 都会产生一个getter setter的机制
对待一个对象 取值也好设置值也好 有一系列的配置与阻止的方法 这就叫对一组数据的劫持
阻拦正常的输出与输入 按照getter setter 执行操作逻辑
function defineProperty() {
var _obj = {};
var a = 1;
Object.defineProperties(_obj, {
a: {
get() {
return '"a"\'s value is ' + a + '.';
},
set(newValue) {
console.log('The value "a" has been designed a new value ' + newValue + '.');
},
},
b: {},
});
return _obj;
}
var obj = defineProperty();
console.log(obj.a);
obj.a = 2;
value 与 writable任意一个都不能与get set 同时出现
如果存在value 或 writable中的一个 还存在get set 会报错
function defineProperty() {
var _obj = {};
var a = 1;
Object.defineProperties(_obj, {
a: {
// value: 1,
writable: true,
get() {
return '"a"\'s value is ' + a + '.';
},
set(newValue) {
console.log('The value "a" has been designed a new value ' + newValue + '.');
},
},
b: {},
});
return _obj;
}
var obj = defineProperty();
console.log(obj.a);
obj.a = 2;
function DataArr() {
var _val = null,
_arr = [];
Object.defineProperty(this, 'val', {
get: function () {
return _val;
},
set: function (newValue) {
_val = newValue;
_arr.push({ val: _val });
console.log('A new value "' + _val + '" has been pushed to _arr');
},
});
this.getArr = function () {
return _arr;
};
}
var dataArr = new DataArr();
dataArr.val = 123;
dataArr.val = 234;
console.log(dataArr.getArr());