首頁  >  文章  >  web前端  >  JavaScript:函數、函數表達式、物件、方法和 this

JavaScript:函數、函數表達式、物件、方法和 this

王林
王林原創
2024-08-07 10:43:23835瀏覽

JavaScript: Functions, Function Expressions, Objects, Methods, and this

簡單的基本功能

這是一個不帶參數的簡單函數:

function hello() {
  console.log('Hello there stranger, how are you?');
}

hello();

這是一個有參數的函數:

function greet(person) {
  console.log(`Hi there ${person}.`);
}

greet('Megan');

我們可以有多個參數,如下:

function greetFullName(fName, lName) {
  console.log(`Hi there ${fName} ${lName}.`);
}

greetFullName('Megan', 'Paffrath');

函數表達式

函數表達式只是寫函數的另一種方式。它們的運作方式仍然與上面相同:

const square = function(x) {
   return x * x;
};

square(2); // 4

高階函數

這些函數與其他函數一起運行/在其他函數上運行,也許它們:

  • 接受其他函數作為參數
  • 回傳一個函數

將另一個函數作為參數的函數的範例是:

function callTwice(func) {
  func();
  func();
}

let laugh = function () {
  console.log('haha');
};

callTwice(laugh);
// haha
// haha

function rollDie() {
  const roll = Math.floor(Math.random() * 6) + 1;
  console.log(roll);
}

callTwice(rollDie);
// random number
// random number

函數傳回函數的範例是:

function makeMysteryFunc() {
  const rand = Math.random();
  if (rand > 0.5) {
    return function () {
      console.log('You win');
    };
  } else {
    return function () {
      alert('You have been infected by a computer virus');
      while (true) {
        alert('Stop trying to close this window.');
      }
    };
  }
}

let returnedFunc = makeMysteryFunc();
returnedFunc();

另一個(更有用的例子)是:

function makeBetweenFunc(min, max) {
  return function (num) {
    return num >= min && num <= max;
  };
}

const isBetween = makeBetweenFunc(100, 200);
// isBetween(130); // true
// isBetween(34); // false

方法

我們可以加入函數作為物件的屬性(這些稱為方法)。

例如:

const myMath = {
  PI: 3.14,
  square: function (num) {
    return num * num;
  },
  // note the 2 diff ways of defining methods
  cube(num) {
    return num ** 3;
  },
};

「this」主要在物件的方法中使用。它用於引用物件的屬性。

const person = {
  first: 'Abby',
  last: 'Smith',
  fullName() {
    return `${this.first} ${this.last}`;
  },
};

person.fullName(); // "Abby Smith"
person.lastName = 'Elm';
person.fullName(); // "Abby Elm"

注意,在物件之外,「this」指的是頂層視窗物件。若要查看其中包含的內容,請在控制台中輸入。通用函數也儲存在 this 物件中:

// defined on its own (outside of an object)
function howdy() {
  console.log('HOWDY');
}

this.howdy(); // HOWDY

以上是JavaScript:函數、函數表達式、物件、方法和 this的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:物件文字下一篇:物件文字