创建同一类的对象:Javascript原型、私有成员、继承

创建同一类的对象:Javascript原型、私有成员、继承,javascript,oop,inheritance,private-members,value-objects,Javascript,Oop,Inheritance,Private Members,Value Objects,有些代码可能会说上千字: /** * Represents an amount of a resource * @param {number} amount * @param {string} type */ function Resource(amount, type) { var nAmount = amount; var sType = type; if (amount < 0) { throw new IllegalAr

有些代码可能会说上千字:

/**
 * Represents an amount of a resource
 * @param {number} amount
 * @param {string} type
 */
function Resource(amount, type) 
{
    var nAmount = amount;
    var sType = type;

    if (amount < 0) 
    {
        throw new IllegalArgumentException("amount has to be positive");
    }

    /**
     * @method Resource
     * @return {number} amount of the resource
     */
    this.getAmount = function() 
    {
        return nAmount;
    };

    /**
     * @method Resource
     * @return {string} resource type
     */
    this.getType = function() 
    {
        return sType;
    };
}

/**
 * Addition of two resources produces a new resource with the sum amount
 * the new object uses the old one as prototype
 * @param {Resource} resource
 * @return {Resource} new Resource object
 */
Resource.prototype.plus = function(resource) 
{
    if (!(resource instanceof Resource && this.getType() == resource.getType())) 
    {
        throw new IllegalArgumentException("resources don't match.");
    }

    var newRes = Object.create(this); // create a new object based on the current one
    // execute the Resource constructor on it
    Resource.call(newRes, this.getAmount() + resource.getAmount(), this.getType());
    return newRes;
};
因此:

Resource.prototype.plus = function(resource) 
{
    // if ... {throw ...}
    return Object.recreate(this, Resource, 
            [this.getAmount() + resource.getAmount(), this.getType()]);
};
也许有人对这个函数的名称有更好的理解。”“重建”是我的第一个想法。你觉得这种模式怎么样?这是一种过度抽象吗?我是否应该将此保存为我确定将从中继承的类?我错过了什么重要的事情吗

编辑:我发现我忘了提到一些重要的东西,这在本文中没有反映出来。使用Object.create可以轻松克隆ValueObject。他们的私人成员是不变的。但是可变的私人成员呢?如果对克隆调用set(),它将在闭包中设置原始原型对象!当my Object.recreate重新创建闭包时,此问题就解决了


那么有没有更好的方法来继承私有变量呢?为什么每个人都用糖来创建类?我已经读了很多关于原型的书,但我仍然不知道它的诀窍。

我认为复制或克隆会是一个更好的名字。这解释了创建此类泛型函数的机制。

多年后回到这里,我可以说我当时编写的代码在混合概念方面存在缺陷。 JavaScript实际上可以通过闭包提供真正的私有变量。但由于ValueObjects无论如何都是不可变的,所以这个私有状态是不能改变的,并且它会使事情变得过于复杂而隐藏它

另外,巧妙的Object.recreate是一种过度抽象的“工厂方法”,如果需要,应该为每个类分别声明

使用组合而不是继承!
Crockford提供了很好的JavaScript见解:

这篇文章很好,但我无法从中获得太多新的东西。owl.clone正是Object.create所在的名称,我认为这个名称更合适。我将针对带有私有变量的非ValueObject的情况编辑我的问题,这些私有变量与“克隆/创建”冲突,但与我的“重新创建”不冲突。
Resource.prototype.plus = function(resource) 
{
    // if ... {throw ...}
    return Object.recreate(this, Resource, 
            [this.getAmount() + resource.getAmount(), this.getType()]);
};