【问题标题】:In JavaScript, is there a way to get closure parameters在 JavaScript 中,有没有办法获取闭包参数
【发布时间】:2018-06-17 04:12:25
【问题描述】:

我有两个文件:

//------------a.js--------------

function a(){
  return '1'
}

var testCase = {
  func(){
    return a()
  }
}

module.exports = testCase

//------------b.js--------------

var testCase = require('./a.js')

//Can I get closure parameters(function a) that not modify a.js?

有没有办法在 JavaScript 中获取闭包参数?谢谢!

【问题讨论】:

  • 你的意思是要像从函数a(a, b)中获取a和b一样获取函数a()的参数吗?
  • 你的问题没有多大意义。您示例中的函数“a”已关闭,但它不包含任何参数。如果是这样,您将不得不在函数 'a 的主体内返回它们或以其他方式将它们发送到其他地方(通过另一个函数)。
  • 您似乎想从b.js 获得对a 的引用?你不能不修改a.js

标签: javascript compilation closures


【解决方案1】:

如果您的意思是从闭包中返回参数列表,例如 get x 和 y from closure run(x, y) {},它位于函数 walk() {} 中,那么下面的代码可能会有所帮助。

    function walk() {
        function run(x, y) {
            return x + y;
        }

        return run;
    }

    var fun = walk();

    fun.getParameters = function () {
        var functionText = this.prototype.constructor.toString();

        return functionText
            .substring(functionText.indexOf('(') + 1, functionText.indexOf(')'))
            .split(',')
            .map(x => x.trim());
    };

    console.log(fun.getParameters());

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多