js之对象

创造对象实例

//法一
var obj=new Object();
//法2
var obj={};
//法1 
var person=new Object();
person.name='sunmenghua';
person.age=24;
//法2 对象字面量表示法  更常用
var person={
 name:'sunmenghua',
age:24
};

访问对象属性:

person.name;
preson["name"];
//在使用方括号语法时,要将访问的属性以字符串德兴市放在方括号中

属性名中若包含可能会导致语法错误的字符,比如空格或者保留字,要用方括号访问!不能用点表示法访问。

person['first name']='menghua';

点表示法比较常用;

属性类型

1.数据属性

有4个描述其行为的特性

writable,(能否修改属性值)

configurable(定义对象的属性能否delete),

enumerable(能否通过for-in 循环返回属性),

value,属性值

通过Object.defineProperty()来修改属性。

Object.defineProperty(对象,属性名,4个特性)

var person={};
Object.defineProperty(person,'name',{
  writable:false,
  configurable:false,
  value:'menghua'
 }
)

2.访问器属性

configurable

enumerable

get 

set

定义多个属性

Object.defineProperties()

var person={};
Object.defineProperties(person,{
  _name:{
    writable:true,
    value:'menghua'
  },
  age:{
    writable:true,
    value:24
  },
  name:{
   get:function(){
    return this._name;  
  },
  set:function(newValue){
   if(newValue>2017)    {
    this._name='sun menghua';
    this.age+=newValue-2017;
  }
}
}
})
person.name=2018
console.log(person.age);
//25
console.log(person._name);
// sun menghua

读取属性的特性

Object.getOwnPropertyDescriptor(对象,属性名).特性

var descriptor=Object.getOwnPropertyDescriptor(person,'name');
console.log(descriptor.value);     //sun menghua
console.log(descriptor.writable);  //true
原文地址:https://www.cnblogs.com/sunmarvell/p/9139001.html