【问题标题】:Javascript call functionJavascript调用函数
【发布时间】:2013-06-10 04:58:41
【问题描述】:

我最近一直在测试一些代码,试图更好地理解 javascript。然后我遇到了我无法理解的call() 函数。

我有以下代码:

function hi(){
    console.log("hi");
}

var bye = function(param, param2){
    console.log(param);
    console.log(param2);
    console.log("bye");
}

如果我打电话给bye.call(hi(), 1, 2),我会得到hi 1 2 undefined

如果我打电话给bye.cal(1,2),我会得到2 undefined bye undefined

据我所知,call() 函数的第一个参数必须是一个函数,然后是我的bye 函数接受的参数量。但是最后一个 undefined 是从哪里来的呢?

【问题讨论】:

    标签: javascript function parameters call


    【解决方案1】:

    第一个参数不必是函数。第一个参数是在函数调用的上下文中设置“this”变量的对象。

    var bye = function(param, param2){
        console.log(param);
        console.log(param2);
        console.log("bye");
        console.log(this.x)
    }
    
    t = {'x': 1};
    
    bye.call(t, 1, 2);
    

    控制台应显示:1、2、“再见”和 1。

    未定义的是你的函数的返回值。

    在您的第一次通话中:

    bye.call(hi(), 1, 2)
    

    你在调用hi()(所以它打印'hi'),返回值没有被使用,1和2是bye的参数。

    在您的第二次通话中:

    bye.cal(1,2)
    

    1 分配给它。 2是param,param2是未定义的。

    【讨论】:

      【解决方案2】:

      你得到了未定义的,因为你的函数没有返回任何东西,它只将输出打印到屏幕上。所以,你的代码可能是这样的:

      var obj = {foo: "hi"};
      var bye = function(param, param2){
          console.log(this.foo);
          console.log(param);
          console.log(param2);
      }
      
      bye.call(obj, 1, 2)   // "hi", 1, 2
      

      您可以阅读here at MDN 以获取有关.call() 的更多信息。

      【讨论】:

        【解决方案3】:

        fn.call() 允许您设置调用函数时this 将具有的值。 this 的值必须是 fn.call() 的第一个参数。

        【讨论】:

          【解决方案4】:

          调用方法需要所有参数单独应用方法需要数组中的所有参数,并通过示例进行说明。

          let solarSystem = {
              sun: 'red',
              moon : 'white',
              sunmoon : function(){
                 let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
                  return dayNight;
              }
          }
          
          let work = function(work,sleep){
              console.log(this.sunmoon()); 
              // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind(),.call(),.apply()
              console.log('i work in '+ work +' and sleep in '+sleep);
          }
          
          let outPut = work.call(solarSystem,'day','night');
          let outPut1 = work.call(solarSystem,['day1','night1']);
          let outPut2 = work.apply(solarSystem,['day2','night2']);

          【讨论】:

            猜你喜欢
            • 2023-03-31
            • 1970-01-01
            • 1970-01-01
            • 2012-09-28
            • 2011-07-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-19
            相关资源
            最近更新 更多