var male = { sex: "male" }; var xiaoming = { name: "xiaoming", school: "xinhua" }; Object.defineProperty(Object.prototype, "extend", { writable: true, enumrable: false, configurable: true, value: function(o) { // 得到所有的自有属性,包括不可枚举属性; var names = Object.getOwnPropertyNames(o); // 遍历它们 for(var i = 0, len = names.length; i < len; i++) { // 如果属性已存在,则跳过; if(names[i] in this) { continue; } // 获得o中的属性的描述符 var desc = Object.getOwnPropertyDescriptor(o, names[i]); // 用它给this创建一个属性 Object.defineProperty(this, names[i], desc); } } }); xiaoming.extend(male); console.log(xiaoming);
时间: 2024-10-12 22:50:09