js属性赋值失效——对象属性详解

673 阅读1分钟
  1. 配置属性和访问属性
Object.defineProperty(obj, prop, descriptor)
// 在对象中添加一个设置了存取描述符属性的示例
var bValue = 38;
Object.defineProperty(o, "b", {
  // 使用了方法名称缩写(ES2015 特性)
  // 下面两个缩写等价于:
  // get : function() { return bValue; },
  // set : function(newValue) { bValue = newValue; },
  get() { return bValue; },
  set(newValue) { bValue = newValue; },
  enumerable : true,
  configurable : true
});
  1. 属性访问o.a 由于原型链的存在,在对象o自有属性找不到o.a时,沿着o.[[prototype]]寻找,直到寻找到a属性或者Object.prototype为止。这就意味着普通的对象都继承了(有例外Object.create(null))Object.prototype的方法,默认会调用属性的getter方法。

  2. 属性修改o.attr = "123"

  • 赋值运算符 引擎会计算o.attr的值,相当于计算表达式的leftvalue,计算rightvalue,将右值赋值给左值
  • attr直接存在于o中,并且attr配置属性是可修改时,修改属性值
  • attr不直接存在于o中,也不在原型链中,则添加attr属性到o上
  • attr在原型链中:
    • 若attr属性可写,则则添加attr属性到o上,
    • 若attr属性不可写,则会忽略掉掉赋值语句,严格模式下会报错
    • 若attr存在setter,attr不会被添加到o,而是调用setter
const object1 = {};
Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});
const object2 = Object.create(object1);
object2.property1 = 77;
// throws an error in strict mode

console.log(object2.property1,object2.hasOwnProperty("property1"));
// 42 false
  • 若要强行添加属性,则必须用object.defineproperty方法