如何在不调用构造函数的情况下复制对象及其原型链?
换句话说,在下面的例子中,函数dup会是什么样子?
class Animal
@sleep: -> console.log('sleep')
wake: -> console.log('wake')
end
class Cat extends Animal
constructor: ->
super
console.log('create')
attack: ->
console.log('attack')
end
cat = new Cat() #> create
cat.constructor.sleep() #> sleep
cat.wake() #> wake
cat.attack() #> attack
dup = (obj) ->
# what magic would give me an effective copy without
# calling the Cat constructor function again.
cat2 = dup(cat) #> nothing is printed!
cat2.constructor.sleep() #> sleep
cat2.wake() #> wake
cat2.attack() #> attack
尽管看起来很痛苦,但这是一个例子中的jsfiddle.
尽管我的例子中只使用了函数,但我还需要这些属性.
解决方法:
function dup(o) {
return Object.create(
Object.getPrototypeOf(o),
Object.getOwnPropertyDescriptors(o)
);
}
它依赖于ES6 Object.getOwnPropertyDescriptors.你可以效仿它. Taken from pd
function getOwnPropertyDescriptors(object) {
var keys = Object.getOwnPropertyNames(object),
returnObj = {};
keys.forEach(getPropertyDescriptor);
return returnObj;
function getPropertyDescriptor(key) {
var pd = Object.getOwnPropertyDescriptor(object, key);
returnObj[key] = pd;
}
}
Object.getOwnPropertyDescriptors = getOwnPropertyDescriptors;
将其转换为coffeescript将留作用户的练习.另请注意,dup浅拷贝拥有属性.