Javascript Object的属性方法

2017-08-28  本文已影响19人  Armin0202

Object.create(prototype[,descriptors])

var o = Object.create({
  "say": function() {
    alert(this.name);
  },
  "name": "Byron"
});
image.png

Object.defineProperty(O,Prop,descriptor) / Object.defineProperties(O,descriptors)

  1. value:值,默认是undefined
  2. writable:是否是只读property,默认是false,有点像C#中的const
  3. enumerable:是否可以被枚举(for in),默认false
  4. configurable:是否可以被删除,默认false;同样可以像C#、Java一样些get/set,不过这两个不能和value、writable同时使用
  5. get:返回property的值得方法,默认是undefined
  6. set:为property设置值的方法,默认是undefined
Object.defineProperty(o, 'age', {
  value: 24,
  writable: true,
  enumerable: true,
  configurable: true
});

Object.defineProperty(o, 'sex', {
  value: 'male',
  writable: false,
  enumerable: false,
  configurable: false
});

console.log(o.age); //24
o.age = 25;

for (var obj in o) {
  console.log(obj + ' : ' + o[obj]);
  /*
            age : 25  //没有把sex : male 遍历出来
            say : function () {
                alert(this.name);
            } 
            name : Byron 
            */
}
delete o.age;
console.log(o.age); //undefined

console.log(o.sex); //male
//o.sex = 'female'; //Cannot assign to read only property 'sex' of #<Object>
delete o.age;
console.log(o.sex); //male ,并没有被删除
Object.defineProperties(o, {
  'age': {
    value: 24,
    writable: true,
    enumerable: true,
    configurable: true
  },
  'sex': {
    value: 'male',
    writable: false,
    enumerable: false,
    configurable: false
  }
});

Object.getOwnPropertyDescriptor(O,property)

var props = Object.getOwnPropertyDescriptor(o, 'age');
console.log(props); //Object {value: 24, writable: true, enumerable: true, configurable: true}

Object.getOwnPropertyNames

console.log(Object.getOwnPropertyNames(o)); //["age", "sex"]

例子中可以看到prototype中的name属性没有获取到


Object.keys()

console.log(Object.keys(o)); //["age"]

上面例子可以看出不可枚举的sex都没有获取的到


Object.preventExtensions(O) / Object.isExtensible

console.log(Object.isExtensible(o)); //true
o.lastName = 'Sun';
console.log(o.lastName); //Sun ,此时对象可以拓展

Object.preventExtensions(o);
console.log(Object.isExtensible(o)); //false

o.lastName = "ByronSun";
console.log(o.lastName); //ByronSun,属性值仍然可以修改

//delete o.lastName;
console.log(o.lastName); //undefined仍可删除属性

o.firstname = 'Byron'; //Can't add property firstname, object is not extensible 不能够添加属性

Object.seal(O) / Object.isSealed

Object.seal(o);
o.age = 25; //仍然可以修改
delete o.age; //Cannot delete property 'age' of #<Object>

Object.freeze(O) / Object.isFrozen

Object.freeze(o);
o.age = 25; //Cannot assign to read only property 'age' of #<Object>
上一篇 下一篇

猜你喜欢

热点阅读