>  기사  >  웹 프론트엔드  >  JavaScript: 함수, 함수 표현식, 개체, 메서드 등

JavaScript: 함수, 함수 표현식, 개체, 메서드 등

王林
王林원래의
2024-08-07 10:43:23833검색

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'는 최상위 창 개체를 나타냅니다. 여기에 포함된 내용을 보려면 콘솔에 입력하세요. 일반 기능도 이 객체에 저장됩니다:

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

this.howdy(); // HOWDY

위 내용은 JavaScript: 함수, 함수 표현식, 개체, 메서드 등의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:객체 리터럴다음 기사:객체 리터럴