let user = {
name : "John",
age : 30
};
user.sayHi = function() {
alert("Hi");
}; // 객체 user에 할당된 sayHi가 메소드.
다시 this로 돌아가서,
let user = {
name : 'John',
age : 30,
sayHi() {
alert(this.name); // this가 현재 객체를 지정함
} //여기까지 메소드
};
user.sayHi();
let user = {
name : 'John',
age : 30,
sayHi() {
alert(user.name); // this대신 user 사용
}
};
let user = {
name : 'John',
age : 30,
sayHi() {
alert(user.name); // Error: cannot read property 'name' of null.
}
};
let admin = user;
user null; // user를 null로 덮어씀
admin.sayHi(); // sayHi()가 다른 값을 참조해서 에러 발생.
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
alert( this.name );
}
user.f = sayHi;
admin.f = sayHi; // 각 객체에서 동일 함수 사용
user.f(); // John (this == user)
admin.f(); // Admin (this == admin)
admin['f'](); // Admin 점과 대괄호는 동일하게 동작함
let user = {
firstName: "보라",
sayHi() {
let arrow = () => alert(this.firstName); //user.sayHi()의 this가 됨.
arrow();
}
};
user.sayHi(); // 보라
calculator 객체에 계산기 메소드 구현하기
조건 1) read() 에선 프롬프트창 띄우고 더할 값 두 개 받기. 입력받은 값은 객체 프로퍼티에 저장
조건 2) sum()은 저장된 두 값의 합 반환
조건 3) mul()은 저장된 두 값의 곱 반환
let calculator = {
sum() {
return this.a + this.b;
},
mul() {
return this.a * this.b;
},
read() {
this.a = +prompt('첫 번째 값:', 0);
this.b = +prompt('두 번째 값:', 0);
}
};
calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );