有没有办法动态获取函数的函数参数名称?
假设我的函数看起来像这样:
function doSomething(param1, param2, .... paramN){
// fill an array with the parameter name and value
// some other code
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何从函数内部获取参数名称及其值的列表到数组中?
我可以覆盖Function对象的行为,以便我可以在每个函数调用之前注入行为,然后继续正常吗?具体来说,(虽然一般的想法本身很有趣)我可以在每个函数调用时登录到控制台而无需在任何地方插入console.log语句吗?那么正常的行为还在继续吗?
我确实认识到这可能会产生严重的性能问题; 即使在我的开发环境中,我也无意进行此操作.但如果它工作,似乎是一个优雅的解决方案,以获得运行代码1000米的视图.我怀疑答案将向我展示更深入的javascript.
对于以下脚本,如何编写一个将所有脚本函数作为数组返回的函数?我想返回脚本中定义的函数数组,以便我可以打印脚本中定义的每个函数的摘要.
function getAllFunctions(){ //this is the function I'm trying to write
//return all the functions that are defined in the script where this
//function is defined.
//In this case, it would return this array of functions [foo, bar, baz,
//getAllFunctions], since these are the functions that are defined in this
//script.
}
function foo(){
//method body goes here
}
function bar(){
//method body goes here
}
function baz(){
//method body goes here
}
Run Code Online (Sandbox Code Playgroud) 我已经使用Java很长一段时间了,很长一段时间我一直在使用GWT(Google Web Toolkit)进行Web开发.它的美妙之处在于我拥有了面向Java对象的构造,并且不会担心它如何被转换为GWT - 让Google来处理它.我对Javascript的了解已经足够,但并不是因为我可以用它进行大量的Web开发.后来我决定我必须对Javascript有更深入和更彻底的了解,这是一个真正的过山车 - 只是在我认为我得到了一些东西,有些东西来证明我错了 - 我只是被误解了.
有什么比stackoverflow更能表达我的关注的地方:我正在寻找一些资源和指向什么是Javascript等同于以下一些Java概念:
Class
instance of a class - object
Member variables
Getters
Setters
Abstract Class
Interface
Inheritance
Access Modifiers
Constructors
Run Code Online (Sandbox Code Playgroud)
我知道其中一些概念,但正如我所说 - 我相信我有一些概念上的困难.如果有人可以指出一个真正的javascript大师试图在这里查明这些概念,我将非常高兴.
开始接触 angular.js,我看到了与回调参数相关的常见模式。ui-router 文档就是一个例子:
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider) {
// Do stuff with ui-router providers
}):
Run Code Online (Sandbox Code Playgroud)
但是,从我所看到的来看,myApp.config回调的参数可能不同,但它仍然会按预期运行:
myApp.config(function(OtherProvider) {
// Do stuff with provider from another service
});
Run Code Online (Sandbox Code Playgroud)
怎么myApp.config知道区别呢?是否正在进行奇怪的魔术内省,或者是否有一些基本的 JS 概念允许这样做?例如:
myApp.config = function(callback) {
var providerNames = callback.argumentNames;
var providers = this.findProviders(providerNames);
};
Run Code Online (Sandbox Code Playgroud)
也许我太习惯Python了,这种功能只有通过一些非常可怕的黑客才能实现。