使用第二个原型扩展对象

时间:2012-08-29 15:48:43

标签: javascript prototype mixins

我有一个原型Node,我创建了几个对象。

在这些对象的生命周期中,我可能需要它们成为ValueNodePropertyNode。我目前通过为每个“子类”使用帮助程序并在两个帮助程序上共享commong接口来处理此问题。想象一下状态模式。

但是,我想通过实际扩展具有附加功能的现有对象而不使用帮助程序来改进此设计。

即:

n = new Node();

...

// n needs to become a ValueNode
// ???

n.methodDefinedForValueNodesOnly();

这可以在javascript中使用吗?这是“好的做法”吗?

2 个答案:

答案 0 :(得分:1)

在mixins上阅读this article之后,我最终使用了以下解决方案(基本上很好地使用了mixins)。

Node = function() {};
Node.prototype.one = function() {alert(1)};

asValueNode = (function() {
  function two() {
    alert(2)
  };
  return function() {
    this.two = two;
    return this;
  }
})();

u = new Node();
// u is a usable Node.
// ...

// Make u a ValueNode
asValueNode.call(u);

u.one();
u.two();

答案 1 :(得分:0)

在JavaScript中,您只需执行一次原型继承。您可以使用一些框架来提供丰富的类子系统,如ExtJSEmber.js等。另一种方法可能是迭代所需对象的属性,然后应用于目标对象。像这样:

function Node( desc ) {
    this.desc = desc;
    this.doNodeThing = function() {
        console.log( "noding for " + this.desc );
    }
}

function FooNode( desc ) {
    this.desc = desc;
    this.doFooNodeThing = function() {
        console.log( "foo noding for " + this.desc );
    }
}

function BarNode( desc ) {
    this.desc = desc;
    this.doBarNodeThing = function() {
        console.log( "bar noding for " + this.desc );
    }
}

function inherit( obj, superObj ) {

    for ( var x in superObj ) {
        if ( typeof superObj[x] == "function" ) {
            obj[x] = superObj[x];
        }
    }
}

var n1 = new Node( "tree node" );
n1.doNodeThing();

var n2 = new Node( "folder node" );
n2.doNodeThing();

inherit( n1, new BarNode() );
n1.doBarNodeThing();
//n2.doBarNodeThing();    <= TypeError: n2.doBarNodeThing is not a function

inherit( n1, new FooNode() );
n1.doBarNodeThing();
n1.doFooNodeThing();
//n2.doFooNodeThing();    <= TypeError: n2.doFooNodeThing is not a function

上面的代码会将函数添加到对象本身,而不是它的原型。

jsFiddle:http://jsfiddle.net/davidbuzatto/3cCGC/