2016-12-04 6 views
0

メソッドチェーン間で別のメソッドを呼び出す方法は?オブジェクト/配列に別のメソッドを適用する

function double(base) { 
 
    return base * 2; 
 
} 
 
function mapDouble(target) { 
 
    return target.map(double); 
 
} 
 

 
var foo = [1,2,3].map(double); 
 
console.log(foo); // => [2, 4, 6] 
 
var bar = mapDouble([1,2,3]); 
 
console.log(bar); // => [2, 4, 6] 
 
var qux = [1,2,3].this.call(mapDouble); 
 
console.log(qux); 
 
// => Error { 
 
// "message": "Uncaught TypeError: Cannot read property 'call' of undefined", 
 
// "filename": "http://stacksnippets.net/js", 
 
// "lineno": 24, 
 
// "colno": 23 
 
// }

私の実際のコードは、(私が書きたい)あなたは例えばのような任意の関数チェーンを作成するには、 "モナド" の施設を作ることができます

[1,2,3].map((value) => { 
    return foo; 
}).filter((value) => { 
    return bar; 
}).this.call(mapDouble); 
+0

ここでfooとbarの値を取得できますか? –

答えて

0

です:

function begin() { 
    return { 
     with: function(x) { 
      this.x = x; 
      return this; 
     }, 
     do: function (f) { 
      this.x = f(this.x); 
      return this; 
     }, 
     end: function() { 
      return this.x; 
     } 
    } 
} 

そして次に

function whatever(ary) { 
    return ary.join('-') 
} 

result = begin() 
    .with([1, 2, 3, 4, 5, 6, 7]) 
    .do(a => a.filter(x => x > 2)) 
    .do(a => a.map(x => x + 100)) 
    .do(whatever) 
    .end(); 
0

構文に問題があります。

function double(base) { 
 
    return base * 2; 
 
} 
 
function mapDouble(target) { 
 
    return target.map(double); 
 
} 
 

 
var foo = [1,2,3].map(double); 
 
console.log(foo); // => [2, 4, 6] 
 
var bar = mapDouble([1,2,3]); 
 
console.log(bar); // => [2, 4, 6] 
 
var qux = mapDouble.call(qux, [1,2,3]); 
 
console.log(qux);

それはあなたが

基本構造を呼び出している関数に引数の引数を取り、このDemoはjavascriptのコール機能の動作を理解するために

を参照してくださいようなものですこの

functionToCall.call(this, arg1, arg2, arg3); 

欲しいのですが、

関連する問題