Dan*_*nor 4 javascript copy prototype-oriented coffeescript
如何在不调用构造函数的情况下复制对象及其原型链?
换句话说,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
Run Code Online (Sandbox Code Playgroud)
就像它的痛苦,我看,这里有一个的jsfiddle的例子.
尽管我的例子中只使用了函数,但我还需要这些属性.
function dup(o) {
return Object.create(
Object.getPrototypeOf(o),
Object.getOwnPropertyDescriptors(o)
);
}
Run Code Online (Sandbox Code Playgroud)
这取决于ES6 Object.getOwnPropertyDescriptors.你可以效仿它.取自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;
Run Code Online (Sandbox Code Playgroud)
将其转换为coffeescript将留作用户的练习.另请注意,dup浅拷贝拥有属性.