728x90

자바스크립트에서 this 는 다른 언어와 다르게 작동한다.

this는 함수를 호출한 방법에 따라 다르게 결정된다.

 

let obj1={

'no':1,

'func1':function(){

console.log('obj1.func1 -->this:'+this.no);

}

}

obj1.func1();//1

ob1의 func1을 실행하면 obj1의 no인 1을 반환한다. 

 

let obj2={

'no':2,

'func2':function(){

console.log('obj2.func2 -->this:'+this.no);

}

}

 

this를 다른 문맥으로 옮기려면 call이나 apply 함수를 사용

obj1.func1.call(obj2);

--------func.call(obj1)----------
obj1.func1 -->this:2

obj2.func2.apply(obj1);

--------func.apply(obj1)----------
 obj2.func2 -->this:1

 

obj1.func1.call(window);

obj1.func1 -->this:undefined

 

this를 처음 호출 함수의 this로 고정 시키려면 bind 함수 사용 (바인드가 여러번 중첩되면 처음 적용된 바인드가 마지막까지 적용된다)

 

function f(){

return this.a;

}

var g = f.bind({ a: "bindedFirst" });

console.log(g()); // bindedFirst

 

var h = g.bind({ a: "bindedSecond" }); // bind는 한 번만 동작

console.log(h()); // bindedFirst

g(): bindedFirst
h(): bindedFirst

 

이벤트 리스너에서 this는 currentTarget

 

$('td').click(function(e){

console.log("this :"+this);

});

this   :[object HTMLTableCellElement]

  

'Javascript' 카테고리의 다른 글

AJAX using JQuery  (0) 2023.09.24
JQuery event  (0) 2023.09.23
JQuery effect  (0) 2023.09.22
JQuery 입문  (1) 2023.09.22
JQuery 이해하기  (0) 2023.09.22

+ Recent posts