JS中函數調用的四種方式


一 以函數形式調用

function fun(){
    alert("hello world");
}
fun();

調用時this指針指向的是函數所屬的對象,當函數沒有被自身的對象調用時,this就是全局變量,在WEB瀏覽器中This指向瀏覽器對象(window對象)

二 函數作為對象方法調用

var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
myObject.fullName();         // 返回 "John Doe"

This指向函數所屬對象本身,也就是myObject

三 使用構造函數調用函數

使用new關鍵字調用函數,即是構造函數

// 構造函數:
function myFunction(arg1, arg2) {
    this.firstName = arg1;
    this.lastName  = arg2;
}

// This creates a new object
var x = new myFunction("John","Doe");
x.firstName;                             // 返回 "John"

構造函數的調用會創建一個新的對象,新對象會繼承構造函數的屬性和方法。

構造函數中 this 關鍵字沒有任何的值。
this 的值在函數調用時實例化對象(new object)時創建。也就是指向了新創建的那個對象

四 使用apply()和call()方法調用

call()方法

function myFunction(a, b) {
    return a * b;
}
myFunction.call(myObject, 10, 2);      // 返回 20

可以看到call方法調用時,第一個參數必須是一個對象,這樣調用的用處即是這里的This指向了函數第一個參數所給的對象

/*定義一個Person類*/ 
function Person(name,age) { 
     this.name=name; 
     this.age=age;
} 
 /*定義一個學生類*/ 
 function Student(name,age,grade) { 
    //Person.apply(this,arguments);//特點:this指代student對象,只接收2個參數,arguments為隱式類數組對象,用來接收傳入的參數;
      Person.call(this,name,age);//特點:this指代student對象,可以接收任意多個參數
      this.grade=grade; 
 } 
 var student =new Student("zhangsan",22,"二年級");//方法Student()也是object的一個實例
 //測試 
 alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);
//學生類里面我沒有給name和age屬性賦值啊,為什么又存在這兩個屬性的值呢,這個就是apply的神奇之處.

apply()

function myFunction(a, b) {
    return a * b;
}
myArray = [10,2];
myFunction.apply(myObject, myArray);   // 返回 20

call()方法和apply()方法的區別即是,apply方法調用函數時,相關實參依次放在第一個參數之后,而apply()傳遞的是一個數組


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM