let user = {
name : 'John',
age :30
};
user.sayHi =function(){
console.log("안녕하세요");
};
user.sayHi(); // 안녕하세요
sayHI
가 메서드let user = {
name : 'John',
age :30
};
function sayHi(){
console.log("하이룽!");
}
user.sayHi = sayHi;
user.sayHi();
user = {
sayHi: function() {
alert("Hello");
}
};
// 단축 구문을 사용하니 더 깔끔해 보이네요.
user = {
sayHi() { // "sayHi: function()"과 동일합니다.
alert("Hello");
}
};
let user = {
name : 'John',
age :30,
sayHi(){
console.log(this.name); // == user.name
}
};
user.sayHi(); //John
let user1 = {
name: "John",
age: 30,
sayHi() {
console.log( user1.name ); // Error: Cannot read property 'name' of null
}
};
let admin = user1;
user1 = null; // user를 null로 덮어씁니다.
admin.sayHi(); // sayHi()가 엉뚱한 객체를 참고하면서 에러가 발생했습니다.
user.sayHi(); //John
let user1 = {name : "John"};
let admin = {name: "Admin"};
function sayy(){
console.log(this.name);
};
user1.f = sayy;
admin.f = sayy;
// 'this'는 '점(.) 앞의' 객체를 참조하기 때문에
// this 값이 달라짐
user1.f();
admin.f();
admin['f'](); //점과 대괄호는 동일하게 동작
※ 객체 없이 호출하기 : this == undefined
function sayHi(){
console.log(this)
}
sayHi() // undefined
⇒ “use strict” 도입된 배경
※ 자유로운 this가 만드는 결과
let user2 = {
firstName: "보라",
sayHi() {
//arrow의 this는 외부함수 user.sayHi()의 this가 됨
let arrow = () => console.log(this.firstName);
arrow();
}
};
user2.sayHi(); // 보라
object.doSomthing()
은 객체를 '행동’할 수 있게 해준다.this
로 객체를 참조 ⇒ this
값은 런타임에 결정this
사용 가능, 단, 함수가 호출되기 전까지 this
엔 값이 할당되지 않음object.method()
같이 ‘메서드’ 형태로 호출하면 this
는 object
참조this
를 가지지 않는다는 점에서 차이 있음.this
를 사용하면, 외부에서 this
값을 가져온다.function makeUser() {
return {
name: "John",
ref() {
return this;
}
};
};
let user = makeUser();
console.log( user.ref().name ); // John
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();
console.log( calculator.sum() );
console.log( calculator.mul() );
let ladder = {
step: 0,
up() {
this.step++;
return this;
},
down() {
this.step--;
return this;
},
showStep() {
alert( this.step );
return this;
}
}
ladder
.up()
.up()
.down()
.up()
.down()
.showStep(); // 1