我正在寻找一种替换对象属性的好方法,同时保持对属性的外部引用。
var Foo = function(){
this.value = 'foo';
this.foo = 1;
};
var Bar = function(){
this.value = 'bar';
this.bar = 1;
};
var obj = {
'property': new Foo()
};
var reference = obj.property;
reference.value; // foo
obj.property = new Bar();
reference.value; // still foo...
您可以在行动here
中看到它显然这是预期的行为。通常你可能不希望reference
被改变,但目前我做了。
我想出了这个功能,但我正在寻找更优雅的东西。
/**
* Replace an objects property maintaining external references
*
* @param {object} obj Object to replace the property on
* @param {string} key Key of the property to replace
* @param {mixed} replacement Value to use as replacement
* @author Robin Cafolla
* @date 2015-02-05
*/
function replaceProperty( obj, key, replacement ) {
var undefined;
for( var i in obj[key] ) {
obj[key][ i ] = undefined;
delete obj[key][ i ];
}
// Set prototype
Object.defineProperty( obj[key], 'prototype', {
enumerable: false,
configurable: true,
writable: true,
value: replacement
});
// Set constructor
Object.defineProperty( obj[key], 'constructor', {
enumerable: false,
configurable: true,
writable: true,
value: replacement.constructor
});
for (var k in replacement) {
obj[ key ][ k ] = replacement[ k ];
}
}
你可以在工作中看到它here