如何将作为参数的函数调用到Function.prototype.bind,并将值作为参数传递给Function.prototype.bind

时间:2016-11-11 04:35:05

标签: javascript

给出

const n = 1;

function value(data) {
  return data === 1 && data;
}

function compare(data, next) {
  return !!(1 == data === next ? next(data) : value(data));
}

function isOne(a, b) {
  return !isNaN(a) && b()
}

function result(x, fn) {
  return fn ? fn(x) : x(n);
}

我们可以致电result()

result(1, function(data) {return compare(data)}); // true

result(1, function(data) {return compare(value(data))}); // true

result(0, compare.bind(value)); // false

result(compare); // true

result(0, compare); // false

 result(1, function(data) {
   return isOne(data, compare.bind(null, data, value))
 }); // true

每个调用模式导致result的返回值为true

我们如何使用valuecompareFunction.prototype.bind或其他方法调用Function.prototype.call作为Function.prototype.apply的参数,而无需明确使用function() {}模式或更改功能valuecompareresult

例如

// where `value` is called with passed `1` as parameter which
// becomes parameter to `compare` call, which becomes parameter
// to `isOne`, with expected return value of `result` being `true`
result(1, isOne.bind(null, compare.bind(null, value)));



const n = 1;

function value(data) {
  console.log("value", data);
  return data === 1 && data;
}

function compare(data, next) {
  console.log("compare", data, next);
  return !!(1 == data === next ? next(data) : value(data));
}

function result(x, fn) {
  console.log("result", x, fn);
  return fn ? fn(x) : x(n);
}

function isOne(a, b) {
  console.log("isOne", a, b);
  return !isNaN(a) && b()
}

console.log(result(1, function(data) {
  return compare(data, value)
})); // true
console.log(result(0, compare.bind(value))); // false
console.log(result(compare.bind(value))); // true
console.log(result(compare)); // true
console.log(result(1, function(data) {
  return isOne(data, compare.bind(null, data, value))
})); // true
 // how can we pass `1` to `value`
 // expected result: `true`, returns `false`
console.log(result(1, isOne.bind(null, compare.bind(null, value))));




0 个答案:

没有答案