2017-03-20 7 views
0

与えられる二つのクラス公開:ExampleWrapper例のインスタンスを取得し、さらなる機能(Decoratorパターン)を得るためにそれをラップはJavaScriptでオブジェクトを飾ると同じシグネチャを

function Example(){ 
this.methodOne = function(/* some args */){...}; 
this.methodTwo = function(/* some args */){...}; 
this.methodThree = function(/* some args*/){...}; 
} 

function ExampleWrapper(example){ 
this.functionFour = function(...){...};  
this.wrapped = example; 
} 

を。

ExampleWrapperのインスタンスから、各関数を手動で定義する必要なく、Exampleの各関数を呼び出せるようにしたいと考えています。 は私が意味する、私は、例の各機能のために、やるExampleWrapper

function ExampleWrapper(example){ 
... 
this.methodOne = function(/* some args */){ 
    return this.wrapped.methodOne(/* same some args*/); 
} 
... 
} 

、その後

var ex = new Example(); 
var wrap = new ExampleWrapper(ex); 
wrap.methodOne(...) 

に次が、それはきちんとした/非常にescalableではありませんでした。

どうすればいいですか? [推測の反射は行く方法かもしれないが、まだそれを使用するために使用されていない]

+1

[プロキシ](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy)をご覧ください。しかし、まずコードが必要なところでサポートされているかどうかを確認してください(http://caniuse.com/#search=proxy)。 – GolfWolf

+0

2つのインスタンス間の 'Object.setPrototypeOf'はどうでしょうか? –

答えて

0

プロトタイプを拡張しようとしましたか?

function Example(){ 
} 
Example.prototype.methodOne = function(/* some args */){console.log('1')}; 
Example.prototype.methodTwo = function(/* some args */){console.log('2')}; 
Example.prototype.methodThree = function(/* some args*/){console.log('3')}; 

function ExampleWrapper(example){ 
    this.functionFour = function(...){...};  
    this.wrapped = example; 
} 

ExampleWrapper.prototype = Example.prototype; 

var test = new ExampleWrapper(new Example()); 
test.functionFour(); 
test.methodOne(...); 
+0

2つのインスタンス間の 'Object.create'または' Object.setPrototypeOf'は、(メソッドのプロトタイプメソッドではなく)インスタンスメソッドも扱うので、より良い選択となります。 –

+0

このようにしますか? var test = Object.setPrototypeOf(新しいExampleWrapper()、新しいExample()); 私の情報でObject.setPrototypeOfを使用するサンプルを提供できますか? – Silvinus

+0

OPの例では、 'Object.setPrototypeOf(wrap、ex)'でもかまいません。欠点は、もちろん 'wrap'では' ex'と 'ExampleWrapper'という2つのプロトタイプを同時に持つことができないので、私の方法かあなたのどちらかです。 –

関連する問題