- Object.defineProperty();//数据属性,参1:要修改的对象,参2:要修改的属性,参3:要修改的配置,有四个可选(Configurable:true/false),表示能否通过delete删除属性而重新定义属性,能否修改属性的特性,能否把属性修改为属性器访问,默认为true; 一旦改为false就不能在更改;(Enumerable),表示能够通过for-in遍历返回属性,默认为true;(Writable),表示能否修改属性,默认为true;(value),表示属性数据值,读取属性时从该位置读,写入属性时,把新值保存到该位置1,默认为undefined;如果调用该方法时,如果不设置以上四个值,默认为false,不调用该方法,默认为true
例:
var person = {
name:"xiaoxiao";
};
Object.defineProperty(person,"name",{
configurable:true;
writable:true,
enumerable:true,
value:"xiao"
});//会改变name的值
访问器属性:Configurable默认为true, Enumerable:默认为true, get:读取属性时调用函数,默认为undefined,set:设置属性时调用的函数,默认为undefined
例:
Object.defineProperty(person,"name",{
get:function(){
return this.name;
}
set:function(newVal){
this.name = newVal;
}
});
person.name = "xiaow"';//会调用set方法
之前使用:person.defineSetter(“name”,function(newVal){
this.name = newVal;
});
person.defineGetter(“name”,function(){
return this.name;
});
2. Object.defineProperties();//用于定义多个属性
var book={};
Object.defineProperties({
year:{
value:2020
},
edition:{
value:2,
},
year:{
get:function(){
return this.year;
},
set:function(newVal){
this.year = newVal;
}
}
});
- Object.getOwnPropertyDescriptor();//取得给定属性描述符,参1:属性所在对象,参2:要去读取的属性描述符的属性名称,返回值是一个对象:如果是数据属性返回数据属性的四个参数,如果是访问器属性,返回访问器属性参数;该方法只能用于实例属性,要取得原型属性描述符,必须直接在原型对象上调用该方法
例:
var des = Object.getOwnPropertyDescriptor(book,year);
console.log(typeof des.get);//function
- Object.getPrototypeOf();//返回对象原型,返回[[Prototype]],用法:Object.getPrototypeOf(构造函数实例)==构造函数.prototype//true,Object.getPrototypeOf(构造函数实例).属性;//用于访问实例属性
- Object.keys();//接受一个对象作为参数,返回一个包含所有可枚举属性得字符串数组
例:
function Person(){
}
Person.prototype.name = "xx";
Person.prototype.age = 18;
Person.prototype.job = "Software";
console.log(Object.keys(Person.prototype));//name,age,job
var p1 = new Person();
p1.name = "xiaoliu";
p1.age = 19;
console.log(Object.keys(p1));//name,age
- Object.getOwnPropertyNames();//用于得到所有实例属性,无论它是否可枚举
例:
console.log( Object.getOwnPropertyNames(Person.prototype));//constructor,name,age,job
- Object.create()方法规范原型式继承,接受两个参数,参1:用作新对象原型的对象和(可选的)一个为新对象额外定义额外的属性对象,在传入一个参数的情况下,与上面object()方法行为相同,第二个参数与Object.defineProperties()方法的格式相同
var per = {
name:"mkh";
};
var anp = Object.create(per,{
name:{
value:"Grey";
}
});