-
[JS] 메서드 호출패턴과 This 바인딩JavaScript 2018. 1. 27. 15:24
메서드 호출패턴
함수가 객체의 프로퍼티면 메서드 호출 패턴으로 호출이 되는데, 메서드 내부의 this는 해당 메서드를 호출한 객체에 바인딩 된다.
var commonctrl = {
name : 'kim',
sayHello : function() {
console.log(this.name);
}
};
commonctrl.sayHello();
프로토타입 객체도 메서드를 갖을 수 있다.
프로토타입 객체 내부에서 사용된 메서드 역시 일반 메서드 방식과 마찬가지로 해당 메서드를 호출한 객체에 바인딩 된다.
var CommonCtrl = function(name) {
this.name = name;
}
CommonCtrl.prototype.getName = function() {
return console.log('My Name ' + this.name);
}
var _commonctrl = new CommonCtrl('Kim');
_commonctrl.getName(); //Kim
CommonCtrl.prototype.name = 'Lee';
CommonCtrl.prototype.getName(); //Lee
'JavaScript' 카테고리의 다른 글
[JS] event.stopPropagation()로 버블업 막기 (0) 2018.02.08 [JS]생성자 호출패턴 This 바인딩 (0) 2018.01.27 [JS] 함수 호출패턴과 This 바인딩 (0) 2018.01.27 [JS]Prototype (0) 2018.01.20 [JS]This (0) 2018.01.07