티스토리 뷰

4.4 Object methods, "this"

객체의 함수를 선언하는 방법은 아래와 같다.

// these objects do the same

user = {
  sayHi: function() {
    alert("Hello");
  }
};

// method shorthand looks better, right?
user = {
  sayHi() { // same as "sayHi: function(){...}"
    alert("Hello");
  }
};

"this" is not bound

this는 서로 다른 객체에 할당되어 따로 동작할 수 있다.

let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() {
  alert( this.name );
}

// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;

// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John  (this == user)
admin.f(); // Admin  (this == admin)

admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)

엄격모드에서는 객체가 없을 때, this를 호출하면 undefined를 반환하지만, 엄격모드가 아닐 때는 전역 객체를 반환한다. (과거에는 이 점을 모른 채로 그냥 this를 사용했었다.)

Arrow functions have no "this"

화살표 함수는 자신을 참조하는 this가 아니라 외부 일반함수의 this와 같은 역할을 한다.

4.5 Constructor, operator "new"

생성자 함수는 일반적인 함수와 기술적으로 거의 동일하다. 다만, 두 가지 컨벤션이 존재한다.

  • 첫 글자는 대문자
  • new 사용

실제로 아래 주석 처리된 코드도 포함해서 수행된다고 생각하면 이해하기 편한 것 같다.

function User(name) {
  // this = {};  (implicitly)

  // add properties to this
  this.name = name;
  this.isAdmin = false;

  // return this;  (implicitly)
}

 

생성자 함수가 아닌 일반 함수를 new 키워드를 사용하여 호출한다면 어떻게 될까?

기술적으로 동일하기 때문에 별 다른 변화는 없다.

Constructor mode test: new.target (거의 쓰이지 않는 syntax, 추후 찾아보기)

Return from constructors

보통, 생성자에는 return문을 사용하지 않지만, 만약  return문을 사용하게 되었을 때, 객체를 리턴하면 this 대신 해당 객체가 반환되고 기본 타입을 리턴하면 무시하고 this를 반환한다.

function BigUser() {

  this.name = "John";

  return { name: "Godzilla" };  // <-- returns this object
}

alert( new BigUser().name );  // Godzilla, got that object

// ----------------------------
function SmallUser() {

  this.name = "John";

  return; // <-- returns this
}

alert( new SmallUser().name );  // John

Methods in constructor

물론 생성자를 통해 메서드도 정의할 수 있다. Java를 아는 입장에선 딱히 특별한 건 없는 것 같다. 오히려, 객체 안에 속하지 않는 함수가 있을 수 있다는 점이 javascript 활용에 주요해 보인다.

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday