zoukankan      html  css  js  c++  java
  • javascript函数的4种调用方式

    在javascript中一共有4种函数调用模式,分别是:方法调用模式、函数调用模式、构造函数调用模式和apply(call)调用模式,这4种模式的主要差异在于如何初始化关键参数this。

    方法调用模式

     当一个函数被保存为对象的一个方法时,我们就称它为一个方法。当一个方法被调用时,this被绑定到该对象。方法可以使用this访问自己所属的对象。

    var testObj = {
      value: 0,
      a: 10,
      b: 20,
      sum: function(){
        this.value = this.a + this.b; 
      }
    };
    
    testObj.sum();
    testObj.value;  // 30

    函数调用模式

    当一个函数并非一个对象的属性时,那么它就是被当做一个函数来调用的。在此模式调用函数时,this被绑定到全局对象。

    value = 100;
    var testObj = {
      value: 10,
      getValue: function(){
        var tempFun = function(){
          console.log(this.value);
        };
        tempFun();
      }
    };
    
    testObj.getValue();	// 100

    从上例中我们可以看到this绑定到了全局对象,这是javascript语言设计上的一个错误,倘若语言设计正确,那么当内部函数被调用时,this应该仍然绑定到外部函数的this变量。但是,有一个很容易的解决方案:如果该方法定义一个变量并给它赋值为this,那么内部函数就可以通过那个变量访问到this,一般按照约定把那个变量命名为that。

    value = 100;
    var testObj = {
      value: 10,
      getValue: function(){
        var that = this;
        var tempFun = function(){
          console.log(that.value);
        };
        tempFun();
      }
    };
    
    testObj.getValue();  // 10
    

      

    构造函数调用模式

     javascript是一门基于原型继承的语言,这意味着对象可以直接从其它对象继承属性。如果在一个函数前面带上new来调用,那么将会创建一个连接到该函数的prototype成员的新对象,同时this会绑定到那个新对象上。

    var Info = function(name){
      this.name = name;
    };
    
    Info.prototype.getName = function(){
      return this.name;
    };
    
    var people = new Info("patten");
    people.getName();  // "patten"
    

      

    apply(call)调用模式

    因为javascript是一门函数式的面向对象的编程语言,因此函数可以拥有方法。

    具体的详见我的另一篇文章 javascript中call和apply方法

  • 相关阅读:
    Different AG groups have the exactly same group_id value if the group names are same and the ‘CLUSTER_TYPE = EXTERNAL/NONE’
    An example of polybase for Oracle
    use azure data studio to create external table for oracle
    Missing MSI and MSP files
    You may fail to backup log or restore log after TDE certification/key rotation.
    Password is required when adding a database to AG group if the database has a master key
    Use KTPASS instead of adden to configure mssql.keytab
    ardunio+舵机
    android webview 全屏100%显示图片
    glide 长方形图片显示圆角问题
  • 原文地址:https://www.cnblogs.com/ArthurPatten/p/3527631.html
Copyright © 2011-2022 走看看