我有一些测试课
TestKlass = (function() {
function TestKlass(value) {
this.value = value != null ? value : 'hello world';
console.log(this.value);
}
return TestKlass;
})();
x = new TestKlass;
x instanceof TestKlass; (gives true)
我有新的空对象
y = {}
y instanceof Object
我可以找到任何方法来为y设置任何属性,比如这样
y.__proto__ = x.__proto__
y.constructor.prototype = x.constructor.prototype
为了得到这个结果
y instanceof TestKlass => true
==================================================== ==
升级版:
所以。我的主要目标是创建 CLONE 功能。现在我的解决方案对我有用。请看这段代码:
JavaScript JS 对象克隆
Object._clone = function(obj) {
var clone, property, value;
if (!obj || typeof obj !== 'object') {
return obj;
}
clone = typeof obj.pop === 'function' ? [] : {};
clone.__proto__ = obj.__proto__;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
value = obj.property;
if (value && typeof value === 'object') {
clone[property] = Object._clone(value);
} else {
clone[property] = obj[property];
}
}
}
return clone;
};
CoffeeScript JS 对象克隆
# Object clone
Object._clone = (obj) ->
return obj if not obj or typeof(obj) isnt 'object'
clone = if typeof(obj.pop) is 'function' then [] else {}
# deprecated, but need for instanceof method
clone.__proto__ = obj.__proto__
for property of obj
if obj.hasOwnProperty property
# clone properties
value = obj.property
if value and typeof(value) is 'object'
clone[property] = Object._clone(value)
else
clone[property] = obj[property]
clone
现在你可以尝试这样做
A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true
它适用于 Moz FF 13。但我认为它不是跨浏览器。并且proto已被弃用。
我认为没有通用的解决方案。但也许它会对某人有所帮助。