js에서this지향에 대한 이해

7606 단어 프런트엔드

js의this에 대한 이해


this 바늘은 줄곧 매우 현학적인 것이다. 이것은 함수가 운행할 때 함수 내부에서 자동으로 생성되는 대상이고 함수체 내부에서만 사용할 수 있다.다음 예는 모두 테스트한 것이니 답안에 대해서는 안심하세요.궁금한 거 있으면 댓글 환영합니다.

순수 함수 호출


이것은 함수의 일반적인 용법으로 전역적인 호출에 속하기 때문에this는 전역을 가리킨다.
가장 간단한 예
var x = 1;
function test() {
   console.log(this.x);
}
test();  // 1

객체로서의 속성


이 때, 누가 이 함수를 호출하면, 함수 내부의this는 누구를 가리킨다
var name = 'window';
var test = {
    name: 'test',
    getName: function(){
        console.log(this.name);
    }
}
test.getName(); // test

구조 함수의 한 속성으로


this는 현재 실례를 가리킨다
var name = 'window';
function Test(){
    this.name = 'test';
    this.getName = function(){
        console.log(this.name);
    }
}
let test = new Test();
test.getName(); // test

call, apply,bind 수정this 지향


call과 apply 방법을 사용하면this의 지향을 수정할 수 있습니다. 이들의 차이점은 다음과 같습니다.
ll this 뒤의 매개 변수는 매개 변수 목록 apply this 뒤의 매개 변수는 하나의 수조bind bind로 귀속되어 새로운 함수를 되돌려줍니다.bind의 중this 뒤의 매개 변수는 귀속 함수에 미리 추가된 매개 변수 목록에 있는 매개 변수입니다.
var test = {
    name: 'test',
    getName: function(extraParam1, extraParam2){
        console.log(this.name, extraParam1, extraParam2);
    }
}

var testCall = {
    name: 'testCall'
}

test.getName.call(testCall,'extraParam1','extraParam2');
// testCall extraParam1 extraParam2

출력된 테스트 콜 대상의name 속성을 볼 수 있으며, 콜 방법 뒤에 있는 매개 변수 목록을 볼 수 있습니다
var test = {
    name: 'test',
    getName: function(extraParam1, extraParam2){
        console.log(this.name, extraParam1, extraParam2);
    }
}

var testApply = {
    name: 'testApply'
}

test.getName.apply(testApply,['extraParam1','extraParam2']);
// testApply extraParam1 extraParam2

apply의 매개 변수는 하나의 매개 변수 그룹입니다
var test = {
    name: 'test',
    getName: function(extraParam1, extraParam2){
        console.log(this.name, extraParam1, extraParam2);
    }
}

var testBind = {
    name: 'testBind'
}

let getNameBind = test.getName.bind(testBind,' ');
getNameBind('extraParam1'); // testBind   extraParam1
test.getName('extraParam1','extraParam2'); // test extraParam1 extraParam2

bind가 새로운 함수를 되돌려줍니다.

화살표 함수


화살표 함수 자체는this대상을 갖추지 못하고 내부의this대상은 부급작용역의 this를 계승한다. 또한 화살표 함수의this는call,apply로 지향을 수정할 수 없지만 부급의this를 수정하여 실현할 수 있다.간단하게 말하면 화살표 함수의this를 알고 싶으면 화살표 함수의 정의 위치를 확인해야지 호출 위치가 아니다.
this.name = 'window';
var test = {
    name: 'getName',
    getName: () => {
        console.log(this.name);
    }
}

var testCall = {
    name: 'testCall'
}

var testApply = {
    name: 'testApply'
}

var testBind = {
    name: 'testBind'
}

test.getName(); // window
test.getName.call(testCall); // window
test.getName.apply(testApply); // window
test.getName.bind(testBind)(); // window

화살표 함수는 테스트 대상의 내부에 정의되고 테스트의 역할 영역은 전역 역할 영역이기 때문에 getName 함수의this는 전역을 가리키며 호출 위치와 무관합니다.또한 call apply bind를 통해this 지향을 직접 수정할 수 없습니다.그리고 다음 예시를 보도록 하겠습니다.
this.name = 'window';
var test = {
    name: 'test',
    getName: function(){
        return () => {
            console.log(this.name);
        }
    }
}

var testCall = {
    name: 'testCall'
}

var testApply = {
    name: 'testApply'
}

var testBind = {
    name: 'testBind'
}

test.getName()(); // test
test.getName.call(testCall)(); // testCall
test.getName.apply(testApply)(); // testApply
test.getName.bind(testBind)()(); // testBind

getName 함수는 화살표 함수를 되돌려줍니다. 따라서 처음에 화살표 함수의 부모 역할역은 getName 함수의 내부 역할역입니다. 따라서this는 getName을 호출하는 사람이 누구를 가리키는지 가리킵니다.그렇다면, GetName의this 지향을 콜, apply,bind로 수정하여 화살표 함수의this 지향을 변경할 수 있습니다.
상기 몇 가지 상황을 말하고 다음은 두 개의 종합 문제를 보겠다
var name = 'window'

var person1 = {
    name: 'person1',
    show1: function () {
        console.log(this.name)
    },
    show2: () => console.log(this.name),
    show3: function () {
        return function () {
            console.log(this.name)
        }
    },
    show4: function () {
        return () => console.log(this.name)
    }
}
var person2 = { name: 'person2' }

person1.show1() // person1
person1.show1.call(person2) // person2

person1.show2() // window
person1.show2.call(person2) // window

person1.show3()() // window
person1.show3().call(person2) // person2
person1.show3.call(person2)() // window

person1.show4()() // person1
person1.show4().call(person2) // person1
person1.show4.call(person2)() // person2

20줄: show1은 일반 함수이고this는 호출 대상을 가리키며 이쪽은person1 호출이기 때문에person1을 가리킨다
21줄:call을 사용하여 show1 함수의 바늘을person2로 가리키기
23행:show2 함수는 화살표 함수이고 부급 작용역은person1 작용역 즉 전역 작용역이기 때문에this는 window를 가리킨다
지 24 줄: 화살표 함수의this 지향은 정의할 때 이미 정해져 있습니다.콜에 따라 수정하지 않기 때문에this는 여전히 window를 가리킨다
26줄: show3은 함수를 되돌려주고 이 되돌아오는 함수를 호출합니다. 이 줄은
let show3 = person1.show3(); 
show3()

첫 번째 상황에 속하며, 함수의 직접 호출,this는 전역을 가리킨다
27행:call을 사용하여 show3 함수를 되돌려주는 함수의this는person2를 가리키며 등가와
let show3 = person1.show3();
show3.call(person2);

제28행: 제26행과 마찬가지로
let show3 = person1.show3.call(person2);
show3();

함수 직접 호출,this는 전역을 가리킨다
30행: show4는 화살표 함수로 되돌아온다. 화살표 함수의this는 계승된 부급 함수인 show4의this이기 때문에 이 화살표 함수의this는 show4의this지향에 달려 있다. 여기는person1로 호출되기 때문에shoe4의this는person1을 가리킨다.
31줄: show4는 화살표 함수로 되돌아온다. 화살표 함수의this는call에 의해 바뀌지 않는다. 여전히 부모의 show4 함수의this에 달려 있다. 여기서person1이 호출되기 때문에 여전히this를 가리키는 것이다.
32줄: show4 함수의this지향을 수정하고person2를 가리켰다. 위에서 말한 바와 같이 이 화살표 함수의this는 show4에 달려 있기 때문에 화살표 함수의this도person2를 가리켰다.
var name = 'window'

function Person (name) {
    this.name = name;
    this.show1 = function () {
        console.log(this.name)
    }
    this.show2 = () => console.log(this.name)
    this.show3 = function () {
        return function () {
            console.log(this.name)
        }
    }
    this.show4 = function () {
        return () => console.log(this.name)
    }
}

var personA = new Person('personA')
var personB = new Person('personB')

personA.show1() // personA
personA.show1.call(personB) // personB

personA.show2() // personA
personA.show2.call(personB) // personA

personA.show3()() // window
personA.show3().call(personB) // personB
personA.show3.call(personB)() // window

personA.show4()() // personA
personA.show4().call(personB) // personA
personA.show4.call(personB)() // personB

이 문제는 하나의 구조 함수이며 두 개의 대상인persona와personB를 예시화한다.22행: 구조 함수 실례의 대상 호출 함수, 함수this는 호출 대상을 가리키기 때문에 여기는persona를 가리킨다
23행:show1 함수의this가call에 의해 수정되고personB를 가리킨다
25행:show2는 화살표 함수로this는 부급 작용역을 가리킨다. 여기가 바로 구조 함수 내부이고 호출 대상에 달려 있다. 여기는persona가 호출하기 때문에this는persona를 가리킨다.
26줄: 화살표 함수의this지향은call에 의해 수정되지 않기 때문에persona를 가리킨다
28줄:show3은 함수를 되돌려줍니다. 전역 호출에 속합니다.this는 전역을 가리킵니다.
let show3 = personA.show3();
show3();

29행:
let show3 = personA.show3();
show3.call(personB);

30행:
let show3 = personA.show3.call(personB);
show3();

32줄: show4는 화살표 함수를 되돌려줍니다. show4의 호출자에 따라 달라집니다. 여기는persona입니다.
33 줄: 화살표 함수의this는call에 의해 수정되지 않습니다. 이것은 show4의 호출자에 의해 결정됩니다.persona를 가리킵니다.
34줄: show4의this지향을 수정하고 화살표 함수의this는show4에 달려 있기 때문에this는personB를 가리킨다
이상은 js에서this지향에 대한 논술입니다.결론: 코드==현학

좋은 웹페이지 즐겨찾기