【问题标题】:Pass function arguments into another function via `bind`通过`bind`将函数参数传递给另一个函数
【发布时间】:2015-07-22 22:17:55
【问题描述】:

这个问题与我的previous question有关,所以我将在此处添加与示例几乎相同的代码。

Ease.bezier = function(mX1, mY1, mX2, mY2) {
    return _bezier.processBezier(mX1, mY1, mX2, mY2);
};

var _bezier = Ease.bezier.prototype;

_bezier.processBezier = function (mX1, mY1, mX2, mY2) {
   return _bezier.render; // this is where I need the `this`, mX1, mY1, mX2, mY2 to be passed into the next function
};

_bezier.render = function(aX){ //the aX value here comes from another object
    var mX1 = [bound function attributes[1]]; // I think you can understand what I mean here
    if (mX1 === mY1 && mX2 === mY2) return aX;

    if (aX === 0) return 0;
    if (aX === 1) return 1; 
    return _bezier.computeBezier(_bezier.gx(aX), mY1, mY2);     
};

现在我需要知道是否可以以某种方式绑定这两个函数,而不会影响来自另一个对象的 aX 值并可以访问第二个函数中的 thismX1, mY1, mX2, mY2 参数。

有可能吗?我该怎么做?

【问题讨论】:

  • processBezier 应该返回什么?
  • render 函数的结果,贝塞尔曲线图中的数字,带有进度和时间轴。
  • “并且可以访问this”是什么意思?这不是正是您之前的问题中回答的吗?
  • 这里没有足够的信息。 .gx() 方法是什么? computeBezier() 方法是什么样的? 使用这个类的一些示例代码是什么?但是有一个提示:您使用_bezier inside 方法的地方可能都应该是this,因为您想引用对象的当前实例,而不仅仅是上面的裸函数原型。
  • @Bergi 我意识到在问上一个问题之前我应该​​知道bind,这实际上是我需要的,下面回答的人给出了很好的答案。谢谢

标签: javascript arguments bind


【解决方案1】:

您可以像这样使用arguments 对象吗??

_bezier.processBezier = function (mX1, mY1, mX2, mY2) {
  return _bezier.render.bind(this, arguments); // <--- bind all the arguments and the context "this"
};

_bezier.render = function(){ // <--- aX is not required anymore instead use arguments object
  var args = arguments[0]; // <--- this corresponds to [mX1, mY1, mX2, mY2]
  var aX = arguments[1]; // <--- this corresponds to aX now
  if (args[0] === args[1] && args[2] === args[3]) return aX; // <--- notice args object here

  if (aX === 0) return 0;
  if (aX === 1) return 1; 
  return _bezier.computeBezier(_bezier.gx(aX), mY1, mY2);     
};

【讨论】:

  • 非常感谢,控制台日志显示得很好。很好的答案。
  • 我确认,您的回答有效。当之无愧的积分,我希望我能获得更多的声望积分:)
  • 我很高兴它有帮助:)
  • 另一个快速的问题。有没有更快的方法来实现这一目标?我读过一些东西,闭包可以比bind 快​​两倍,你知道这是怎么回事吗?
猜你喜欢
  • 2012-09-10
  • 2012-09-25
  • 2020-10-03
  • 2014-01-06
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多