나는 최근에 "JavaScript : good parts"를 읽고 이해할 수없는 예제 중 하나를 인용하기 시작했습니다. 내가 that
(var that = this
)를 사용하면 내가 myObject
의 필드, val
를 참조하고JavaScript 함수 호출
var add = function(a,b) {
return a+b;
};
var myObject = {
val: 0,
increment: function(inc) {
this.val += typeof inc == 'number' ? inc : 1;
}
};
myObject.increment(12);
myObject.increment();
// till this line, the val is equal to 13
// function invocation
myObject.double = function() {
var that = this;
// inner function #1
var helper = function() {
that.val = add(that.val, that.val);
};
// inner function #2
var test = function(){
this.val = add(this.val, this.val);
};
helper(); // the val is equal to 26
// test(); // the val is equal to 13
};
: 나는 원래 예에 test
기능을 추가했습니다. 또한 내 test
함수에서 이것을 사용할 때 같은 객체의 동일한 필드를 참조하고 있지만 대답이 다릅니다. 모든 설명은 인정 될 것이다.
예제 코드에 감사드립니다. – Yar