如何在不调用其构造函数的情况下复制对象及其原型(prototype)链?
换句话说,函数 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
浅拷贝拥有自己的属性。
关于javascript - 如何在不调用其构造函数的情况下复制对象及其原型(prototype)链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8566269/