ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript: 関数、関数式、オブジェクト、メソッド、およびこれ

JavaScript: 関数、関数式、オブジェクト、メソッド、およびこれ

王林
王林オリジナル
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();

これは 1 つの引数を取る関数です:

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: 関数、関数式、オブジェクト、メソッド、およびこれの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。