var obj={name:'John'}
var obj1=Object.create(obj);
这一行将在obj1的原型上添加属性。 因此,如果我将使用console.log(obj1.name),因为当前对象上不存在属性,它将在原型链中上升并获取name属性及其值。
现在考虑
var obj2={lname:'Mart'}
obj2=Object.create(obj);
现在它会将name
属性添加到其原型中,这很好。
但是所有的属性都没有了。 (我可以从crokford的shim实现中想到它的原因,其中创建了新对象,将属性添加到其原型中然后返回它们)
我可以obj2._ _proto_ _=obj;
(对所有浏览器不兼容浏览器)
现在我的问题是,如果object.create
的好方法是删除属性,我应该如何向我的原型添加属性,以便obj2
的自有属性不会被删除。
我不想使用构造函数。除了上面两个之外,还有其他方法可以为原型添加属性吗?请点亮。
答案 0 :(得分:0)
你想要的是Object.assign
。来自MDN:
Object.assign()方法用于复制all的值 枚举从一个或多个源对象到目标的自有属性 宾语。它将返回目标对象。
var obj1 = { a: "A", b: "B" };
var obj2 = { b: "XXX", c: "C" };
Object.assign(obj1, obj2);
// target ^ ^ source
console.log(obj1);
//=> { a: "A", b: "XXX", c: "C" }
// ^ the property from `obj2` overwrote the existing property
如果要扩展原型,只需分配原型而不是对象本身,例如:
Object.assign(Vector.prototype, Paths.prototype);
// Vector objects now include the methods from Paths
请注意,这是一种ES2015方法。因此,在部署时,您需要使用polyfill来支持旧版浏览器,这些浏览器在MDN页面上提供:
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}