2011-07-03 20 views
7

私はthis article on polymorphic callable objectsを見て、動作させようとしていましたが、実際に多形ではないか、少なくともプロトタイプチェーンを尊重していないようです。javascript "polymorphic callable objects"

このコードではではなく"hello there"と表示されます。

このメソッドはプロトタイプでは機能しませんか、何か間違っていますか?

var callableType = function (constructor) { 
    return function() { 
    var callableInstance = function() { 
     return callableInstance.callOverload.apply(callableInstance, arguments); 
    }; 
    constructor.apply(callableInstance, arguments); 
    return callableInstance; 
    }; 
}; 

var X = callableType(function() { 
    this.callOverload = function(){console.log('called!')}; 
}); 

X.prototype.hello = "hello there"; 

var x_i = new X(); 
console.log(x_i.hello); 
+1

私はちょうどあなたの肖像画と名前に感動しました。私は彼の名前Shuren Zhouを仮定する。 – xis

答えて

6

あなたはこの変更する必要があるだろう。これに

var X = callableType(function() { 
    this.callOverload = function(){console.log('called!')}; 
}); 

var X = new (callableType(function() { 
    this.callOverload = function(){console.log('called!')}; 
})); 

お知らせnewなどcallableType呼び出しを括弧で囲みます。

括弧はcallableTypeを呼び出して、newのコンストラクタとして使用される関数を返します。


EDIT:

var X = callableType(function() { 
    this.callOverload = function() { 
     console.log('called!') 
    }; 
}); 

var someType = X();  // the returned constructor is referenced 
var anotherType = X(); // the returned constructor is referenced 

someType.prototype.hello = "hello there"; // modify the prototype of 
anotherType.prototype.hello = "howdy";  // both constructors 

var some_i = new someType();   // create a new "someType" object 
console.log(some_i.hello, some_i); 

var another_i = new anotherType();  // create a new "anotherType" object 
console.log(another_i.hello, another_i); 

someType();  // or just invoke the callOverload 
anotherType(); 

私は実際にどのように/どこ/なぜあなたはこのパターンを使用したいかわからないが、私はいくつかの良い理由がありますと仮定します。

+0

おそらく私は何か間違っていますが、これはインスタンス呼び出しを呼び出すことができなくなるようです。 'x_i()'は、 "object not function"の行に沿って例外をスローします。 –

+0

@luxun:そのような 'new'インラインを使うと、直ちにコンストラクタとして' callableType'という形式で返された関数を呼び出しています。あなたが欠けているのは、 'X'から返されたコンストラクタではなく、' X'のプロトタイプにコードが追加されたことです。私が持っている方法では、 'X'はコンストラクタ自身になりますが、代わりに別の変数で参照することができます。私は更新を追加します。 – user113716

+0

さて、わかりました。実際には*インスタンスを呼び出し可能にすると思っていましたが、これは当てはまりません。 –