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

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

问题描述

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

addTogether(2)(3);

这是我得到的基本功能:

function addTogether() {返回;}

当我运行下面的代码时:

function addTogether() {返回参数;}

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

<块引用>

类型错误:addTogether(...) 不是函数

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

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

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

帮助,非常感谢.

解决方案

不要将其视为两组独立的参数.把它想象成你正在调用另一个函数(你是).函数是 JavaScript 中的一等值,因此您可以像使用任何其他值一样使用它们.这包括从函数中返回它们.

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

函数还可以使用任何父作用域中存在的值.粗略地说,执行此操作的函数称为闭包.>

function createGetX(x) {返回函数(){//由于 x 在父作用域中,我们可以在这里使用它返回 x;}}var 一 = createGetX(1);console.log(one());//总是console.log(one());//返回console.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天全站免登陆