Javascript 对象。创建对象的擦除属性
此行将在obj1的原型上添加属性。 所以,若我使用console.log(obj1.name),由于当前对象上不存在属性,它将在原型链中上升,并获得name属性及其值Javascript 对象。创建对象的擦除属性,javascript,object,Javascript,Object,此行将在obj1的原型上添加属性。 所以,若我使用console.log(obj1.name),由于当前对象上不存在属性,它将在原型链中上升,并获得name属性及其值 现在考虑 var obj={name:'John'} var obj1=Object.create(obj); 现在,它将在原型中添加name属性,这很好。 但所有的属性都消失了。(原因我可以从crokford的shim实现中想到,其中创建了新对象,将属性添加到其原型中,然后返回它们) 我可以通过obj2.\uu proto\u
现在考虑
var obj={name:'John'}
var obj1=Object.create(obj);
现在,它将在原型中添加name
属性,这很好。
但所有的属性都消失了。(原因我可以从crokford的shim实现中想到,其中创建了新对象,将属性添加到其原型中,然后返回它们)
我可以通过obj2.\uu proto\uuj=obj代码>(并非所有浏览器都对浏览器友好)
现在我的问题是,如果object.create
的好方法是擦除属性,那么我应该如何向原型中添加属性,以便obj2
的自身属性不会被擦除
我不想使用构造函数。除了上述两种方法之外,还有其他方法可以将属性添加到原型中吗。请放灯。您需要的是对象。分配。从:
assign()方法用于复制所有
从一个或多个源对象到目标对象的可枚举自身属性
对象它将返回目标对象
例子
如果要扩展原型,只需将其指定给原型而不是对象本身,例如:
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
兼容性
请注意,这是一种ES2015方法。因此,在部署时,您需要一个polyfill来支持旧浏览器,这在MDN页面上提供:
Object.assign(Vector.prototype, Paths.prototype);
// Vector objects now include the methods from Paths
if(type of Object.assign!=“function”){
(功能(){
Object.assign=函数(目标){
"严格使用",;
如果(目标==未定义| |目标===空){
抛出新的TypeError('无法将未定义或null转换为对象');
}
var输出=对象(目标);
for(var index=1;index
如果重新分配obj2
,则重新分配,旧值将消失,就像重新分配var x=1一样;x=2代码><代码>对象。创建
未“擦除属性”;如果您想更详细地了解这一点,请执行var obj2={lname:'Mart'};var obj3=obj2;obj2=Object.create(obj)代码>。现在看一下obj3
和obj2
obj3
仍然具有lname
属性。@Barmar obj2没有lname属性。请检查……现在的要点是将属性从第二个对象添加到第一个对象的原型的好方法。我不认为有一种内置的方式可以合并对象。如果您使用jQuery,您可以使用$.extend
。是的,这很酷,但为什么是downvote呢。
Object.assign(Vector.prototype, Paths.prototype);
// Vector objects now include the methods from Paths
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;
};
})();
}