DIV CSS 佈局教程網

JavaScript 函數調用方式與參數傳遞解析
編輯:JavaScript基礎知識     

JavaScript 函數有多種調用方式,不同調用方式會影響 this 的指向。理解這些差異,是掌握 JavaScript 物件導向與事件處理的關鍵。

作為普通函數調用

function myFunction(a, b) {
  return a * b;
}

myFunction(10, 2);

在瀏覽器中,這類函數通常屬於 window 物件。

作為物件方法調用

const myObject = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  }
};

myObject.fullName();

此時 this 指向 myObject。

作為建構函式調用

function MyFunction(arg1, arg2) {
  this.firstName = arg1;
  this.lastName = arg2;
}

const x = new MyFunction('John', 'Doe');
console.log(x.firstName);

使用 call 與 apply

call() 與 apply() 可以改變 this 的指向:

myFunction.call(myObject, 10, 2);
myFunction.apply(myObject, [10, 2]);

兩者差異在於第二個參數:call 接受參數列表,apply 接受陣列。

arguments 物件

函數內建 arguments 物件,可取得實際傳入的參數:

function sumAll() {
  let sum = 0;
  for (let i = 0; i < arguments.length; i += 1) {
    sum += arguments[i];
  }
  return sum;
}

console.log(sumAll(1, 123, 500, 115, 44, 88));

若函數修改物件屬性,通常會影響外部物件;若修改的是原始值參數,則不會影響外部變數。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved