咱们可使用getOwnPropertyDescriptor来查看属性状态bash
var o = { a: 1 };
o.b = 2;
//a 和 b 皆为数据属性
Object.getOwnPropertyDescriptor(o,"a") // {value: 1, writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(o,"b") // {value: 2, writable: true, enumerable: true, configurable: true}
复制代码
若是想改变属性的特征或者定义访问器属性可使用Object.defineProperty函数
var o = { a: 1 };
Object.defineProperty(o, "b", {value: 2, writable: false, enumerable: false, configurable: true});
//a 和 b 都是数据属性,但特征值变化了
Object.getOwnPropertyDescriptor(o,"a"); // {value: 1, writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(o,"b"); // {value: 2, writable: false, enumerable: false, configurable: true}
o.b = 3;
console.log(o.b); // 2
复制代码
一样也可使用get或者set来建立访问器属性性能
var o = { get a() { return 1 } };
console.log(o.a); // 1
复制代码
function mynew(){
let obj = {};
let con = [].shift.call(arguments)
obj.__proto__ = con.prototype;
let r = con.call(obj,arguments)
return r instanceof Object ? r : obj;
}
复制代码
Object.create = function(prototype){
var cls = function(){}
cls.prototype = prototype;
return new cls;
}
复制代码