What's this?
실행 기 바 인 딩 특성 상 자 바스 크 립 트 의
this
의 미 는 매우 많 습 니 다. 전체 대상, 현재 대상 또는 임 의 대상 일 수 있 습 니 다. 이것 은 함수 호출 방식 에 달 려 있 습 니 다.함수 사용 장소 에 따라 this 의 값 이 달라 집 니 다.그러나 하나의 총체적인 원칙 이 있다. 그것 이 바로 this 가 가리 키 는 것 은 함 수 를 호출 하 는 그 대상 이다
함수 호출
함수 가 직접 호출 될 때 this 는 전역 대상 에 연 결 됩 니 다.브 라 우 저 에서 window 는 이 전역 대상 입 니 다.
console.log(this); //Window
function fn1(){
function fn2(){
console.log(this);
}
}
fn1(); //Window
플러그 인 호출
함수 가 포 함 된 내부 함수
this
는 부모 함수 가 아니 라 전역 변수 입 니 다.console.log(this); //Window
function fn1(){
function fn2(){
console.log(this);
}
fn2()
}
fn1(); //Window
setTimeout、setInterval
문서 가 져 오기:
document.addEventListener('click', function(e){
console.log(this);
var _this = this;
setTimeout(function(){
console.log(_this);
}, 200);
}, false);
대상 방법 으로 호출
JavaScript 에서 함수 도 대상 이기 때문에 함 수 는 하나의 대상 의 속성 으로 할 수 있 습 니 다. 이때 이 함 수 는 이 대상 의 방법 이 라 고 불 립 니 다. 이러한 호출 방식 을 사용 할 때 this 는 자 연 스 럽 게 이 대상 에 연결 되 어 있 습 니 다.
var obj1 = {
name: 'Byron',
fn : function(){
console.log(this);
}
};
obj1.fn();//Object {name: "Byron", fn: function}
var fn2 = obj1.fn;
fn2(); //window, window.fn2()
Function.prototype.bind
bid, 새로운 함 수 를 되 돌려 주 고 함수 내부 의 this 를 들 어 오 는 첫 번 째 매개 변수 로 합 니 다.
document.addEventListener('click', function(e){
console.log(this);
setTimeout(function(){
console.log(this);
}.bind(this), 200);
}, false);
call 과 apply 를 사용 하여 this 설정 하기
var value = 100;
var obj = {
value: 200
}
function fn(a,b){
console.log(this.value + a + b)
}
fn(3,4) //107
fn.call(obj,3,4) //207
fn.apply(obj, [3,4]) //207
배열 의 최대 값 을 얻다.
var arr = [1,3,12,3]
console.log( Math.max.apply(null, arr) ) //12
맞 춤 문자열
function joinStr(){
//1.
console.log( Array.prototype.join.call(arguments, '-'))
//2.
var join = Array.prototype.join.bind(arguments);
console.log(join('-'))
}
joinStr('a','b','c')
세 가지 변수
function ClassA(){
var a = 1; // ,
this.b = 2; // ,
}
ClassA.c = 3; // , ,
console.log(a); // error
console.log(ClassA.b) // undefined
console.log(ClassA.c) //3
var classa = new ClassA();
console.log(classa.a);//undefined
console.log(classa.b);// 2
console.log(classa.c);//undefined
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.