【问题标题】:Javascripts call function with parameters [closed]带参数的Javascript调用函数[关闭]
【发布时间】:2014-04-24 22:25:10
【问题描述】:

示例:

function MyDev() {
   this.someFunc;
   this.run = function() {
       if (typeof this.someFunc == 'function') {
          this.someFunc();
       } 
   }
}

var dev = new MyDev();
dev.someFunc = function(args1, args2,...) {
   //dosomething...
}
dev.run();

现在,调用函数dev.run()时,如何调用带参数的函数abcdef?有人可以帮助我吗???

【问题讨论】:

标签: javascript


【解决方案1】:

Javascript 有一个名为“参数”的关键字。 在函数中,这是一个数组,其中包含传递给该函数的所有参数。

    function hehey(){
        console.log(arguments);
        // The console will show an array with ['hello', 'foo', 'bar', 'world']
    }
    hehey('hello', 'foo', 'bar', 'world');

所以你可以通过像这样从父函数中发送参数关键字来使用它:

function MyDev() {
    this.someFunc;
    this.run = function() {
        if (typeof this.someFunc == 'function') {
            this.someFunc(arguments);
        }
    }
}

var dev = new MyDev();
dev.someFunc = function(test, test2) {
    console.log(test, test2);
}
dev.run("hello", "world");

有关.apply 方法的更多信息:http://msdn.microsoft.com/en-us/library/ie/4zc42wh1(v=vs.94).aspx

【讨论】:

  • var args = ["toan", 23]; this.someFunc.apply(null, args);它可以工作,但是 this.someFunc.apply(null, arguments);它不起作用,因为参数总是 [];如何获取函数的参数?
  • 我已对其进行了编辑以显示示例。我已经测试了代码,它似乎可以工作:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 2022-08-09
相关资源
最近更新 更多