4

如何在不调用其构造函数的情况下复制对象及其原型链?

换句话说,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

尽管在我的示例中只使用了函数,但我也需要这些属性。

4

2 回答 2

5
function dup(o) {
    return Object.create(
        Object.getPrototypeOf(o),
        Object.getOwnPropertyDescriptors(o)
    );
}

这依赖于 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;

现场示例

将其转换为咖啡脚本留给用户作为练习。另请注意,dup浅拷贝具有自己的属性。

于 2011-12-19T19:20:33.107 回答
0

您应该使用特殊__proto__成员,它在每个对象中都可用,并且是指向对象类的原型的指针。以下代码是纯javascript:

function dup(o)
{
    var c = {};

    for (var p in o)
    {
        c[p] = o[p];
    }
    c.__proto__ =  o.__proto__;

    return c;
}
于 2011-12-19T19:54:35.023 回答