LoginSignup
1
0

More than 5 years have passed since last update.

객체 메소드 "this"

Posted at

객쳄메쏘드 예제

file.js
let user = {
    name: 'John',
    age: 30
};
user.sayHi = function() {
    alert("hello");
}
user.sayHi();// hello
file.js
let user = {

}
//함수선언
function sayHi() {
    alert("Hello");
}
user.sayHi = sayHi;
user.sayHi(); // Hello
file.js
let user = {
    sayHi = function() {
        alert("Hello");
    }
}

let user = {
    sayHi() { // 위와 같은 함수입니다.
        alert("Hello");
    }
}

정확히 이야기하면 완전하게 같지는 않고 미묘한 차이가 있다

file.js
let user = {
    name: "John",
    age: 30,
    sayHi() {
        alert(this.name);
    }
}

user.sayHi(); // John
file.js
let user = {
  name: "John",
  age: 30,

  sayHi() {
    alert(user.name); // 신뢰할수 없는 코드이다.
  }

};

//만일 let admin = user 하면 카피한 객체의 user.name 을 찿을수 없게 된다.

let user = {
    name: "John",
    age: 30,
    sayHi() {
        alert(user.name);
    }
}

let admin = user;
user = null;
admin.sayHi(); //error;

file.js
let user = {name: "John"}
let admin = {name: "admin"}
function sayHi() {
    alert(this.name);
}

user.f = sayHi;
admin.f = sayHi;

user.f(); // johnb
admin.f(); // admin
admin['f'](); //admin  괄호표기로 함수를 호출할수 있다
file.js
function sayHi() {
    alert(this)
}

sayHi(); //undefiend

일반적으로 this객체없이 사용하는 함수의 호출은 정상적인 것이 아니라 프로그래밍 실수입니다. 함수가 가지고있는 경우, this일반적으로 객체의 컨텍스트에서 호출되도록되어 있습니다.

file.js

let user = {
    name : "John",
    go: function() {
        alert(this.name)
    }
};

(user.go)();

대괄호 (user.go)는 아무 것도하지 않습니다.
보통 그들은 작업 순서를 설정하지만 ., 어쨌든 점이 먼저 작동하므로 효과가 없습니다.
세미콜론 만 중요합니다.

file.js
let obj, method;
obj = {
    go: function() {
        alert(this);
    }
}
obj.go(); // [object Object]
(obj.go)();// [object Object]
(method = obj.go)();//undefined
(obj.go||obj.stop)();//undefined

계산기

file.js
let calculator = {
    sum() {
        return this.a + this.b;
    },    
    mul() {
        return this.a * this.b
    },    
    read() {
        this.a = +prompt('a?',0);// +prompt 숫자로 인식
        this.b = +prompt('b?',0);
    }
}

calculator.read();
alert(calculator.sum());
alert(calculator.mul());
file.js
let ladder = {
    step : 0,
    up() {
        this.step++;
    },
    down() {
        this.step--;
    },
    showStep : function() {
        alert(this.step);
    }
};

ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1

chaining

file.js
let ladder = {
    step : 0,
    up() {
        this.step++;
        return this;
    },
    down() {
        this.step--;
        return this;    
    },
    showStep : function() {
        alert(this.step);
        return this;
    }
};
// chaining 모든객체에서 this를 반환
ladder.up().up().down().showStep(); // 1

객체를 반환해서 체이닝기법으로 사용할수도 있다.
자바스크립트 라이브러리에서 많이 쓰인다.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0