通用功能?

时间:2016-01-25 14:00:26

标签: javascript node.js

我试图找出这个问题的答案:

  

不使用Javascript的绑定功能,实现魔术功能,以便:

var add = function(a, b) { return a + b; }
var addTo = add.magic(2);

var say = function(something) { return something; }
var welcome = say.magic('Hi, how are you?');

addTo(5) == 7;
welcome() == 'Hi, how are you?';

我想我需要使用电话或申请,但我不知道,如果有人能指出我正确的方向或提供一些文献,我将非常感激。

2 个答案:

答案 0 :(得分:1)

您可以使用闭包和apply function



Function.prototype.magic = function(){
  var self = this;
  var args = Array.from(arguments);
  
  return function(){
    return self.apply(null, args.concat(Array.from(arguments)));
  }
}


var add = function(a, b) { return a + b; }
var addTo = add.magic(2);

var say = function(something) { return something; }
var welcome = say.magic('Hi, how are you?');

console.log(addTo(5) == 7);
console.log(welcome() == 'Hi, how are you?');



 您也可以在MDN上查看Polyfill for bind函数

答案 1 :(得分:1)

请参阅以下代码:

double need = ((double)a.size()) / b.size();
double have = 0;
size_t pos = 0;
for (size_t i = 0 ; i != a.size() ; i++) {
    if (need >= have+1) {
        b[pos] += a[i];
        have++;
    } else {
        double frac = (need-have); // frac is less than 1 because of the "if" condition
        b[pos++] += frac * a[i];   // frac of a[i] goes to current element of b
        have = 1 - frac;
        b[pos] += have * a[i];     // (1-frac) of a[i] goes to the next position of b
    }
}
for (size_t i = 0 ; i != b.size() ; i++) {
    b[i] /= need;
}