在方法内执行方法 [英] Executing a method inside a method

查看:79
本文介绍了在方法内执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在FreeCodeCamp中进行JavaScript练习,我的代码应该使用的测试用例之一是一个函数调用,如下所示:

  addTogether(2)(3); 

这是我给出的简单功能:

  function addTogether(){
return;
}

当我运行以下代码时:

  function addTogether(){
return arguments;
}

在编辑器提供的控制台中,我得到:


TypeError:addTogether(...)不是函数


说明提示使用参数对象,它适用于只有一个参数对象的测试用例函数调用(即 addTogether (2,3); ),但不是我上面显示的那个。



当我们使用上面显示的格式时,有没有办法访问/利用单独的参数对象?



注意:我不想要任何答案来解决问题,只需要有关访问这些函数调用参数的任何技术的信息。 / p>

帮助,非常感谢。

解决方案

不要想到它作为两组独立的论点。想一想你正在调用另一个函数(你是)。函数是JavaScript中的第一类值,因此您可以像使用任何其他值一样使用它们。这包括从函数返回它们。



  var f = function(y){ console.log('f:',y);}; var getF = function(x){console.log('getF:',x); return f;}; getF(1)(2);  



函数还可以使用任何父作用域中存在的值。简而言之,执行此操作的功能称为关闭。



  function createGetX(x){return function(){//因为x在父范围,我们可以在这里使用它返回x; var one = createGetX(1); console.log(one()); // Alwaysconsole.log(one()); // returnsconsole.log(one()); //一个 


I'm currently working on a JavaScript exercise in FreeCodeCamp, and one of the test-cases my code should work with is a function call that looks like this:

addTogether(2)(3);

here is the bare-bones function I'm given:

function addTogether() {
  return;
}

When I run the code below:

function addTogether() {
  return arguments;
}

In the console, that the editor provides, I get:

TypeError: addTogether(...) is not a function

The instructions hint at using the arguments object, and it works well with test-case function calls that only have one argument object (i.e. addTogether(2, 3);), but not with the one I've shown above.

Is there a way to access/utilize the separate argument objects when they're in the format I showed above?

Note: I don't want any sort of answer to solve the problem, just info on any techniques on accessing the arguments of these type of function calls.

Help, is greatly appreciated.

解决方案

Don't think of it as two separate sets of arguments. Think of it as you're calling another function (which you are). Functions are first-class values in JavaScript so you can use them just like any other value. This includes returning them from functions.

var f = function(y) {
  console.log('f:', y);
};

var getF = function(x) {
  console.log('getF:', x);
  return f;
};

getF(1)(2);

Functions can also use values that exist in any parent scope. Loosely speaking, functions which do this are called closures.

function createGetX(x) {
  return function() {
    // Since x is in the parent scope, we can use it here
    return x;
  }
}

var one = createGetX(1);
console.log(one()); // Always
console.log(one()); // returns
console.log(one()); // one

这篇关于在方法内执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆