나는 항상 JavaScript에서 이것에 대해 그럴듯한 느낌을 받았습니다. 오늘 나는 갑자기 깨달았다 고 느꼈다. 여기에 기록하겠습니다.
먼저 밤나무를 봅시다 :
<! docType html> <html> <head> <meta charset = "utf-8"> carkey = document.getElementByid ( 'car_key'); carkey.onclick = function () {this.start (); };} return this;} tesla = new car (); tesla.turnkye (); </script> </head> <body> <input type = "button"id = "car_key"value = "test"/> </body> </html>언뜻보기에는이 코드에 문제가 없지만 이에 대한 잘못된 이해는 궁극적으로 잘못된 결과로 이어집니다. 우리는 CAR_KEY 요소에 대한 클릭 이벤트를 바인딩하고 자동차 클래스에서 바인딩 클릭 이벤트를 중첩하면이 DOM 요소가 자동차 의이 상황에 액세스 할 수 있다고 생각합니다. 이 방법은 합리적으로 보이지만 불행히도 작동하지 않습니다.
JavaScript 에서이 키워드는 항상 실행되는 범위의 소유자를 가리 킵니다.
위의 문장을주의 깊게 이해하십시오. 아시다시피, 기능 호출은 새로운 범위를 생성하고 약간의 onclick 이벤트가 트리거되며, 이것은 자동차 클래스 대신 DOM 요소를 가리 킵니다.
그렇다면 제대로 작동하도록 어떻게해야합니까? 우리는 일반적으로 범위로 인한 문제를 피하기 위해 로컬 프리 변수 (예 : 많은 프레임 워크에 반영되는 _this, self, me 등)에 이것을 할당합니다. 여기서 우리는 로컬 변수를 사용하여 이전 방법을 무시합니다.
<! docType html> <html> <head> <meta charset = "utf-8"> <title>이 </title> </head> <body> <input type = "id ="id = "car_key"value = "test"/<script type = "text/javaScript"> car = function () {this.start = function () {console.log ( 'car starting');}; this.turnkye = function () {var that = this; var carkey = document.getElementByid ( 'car_key'); carkey.onclick = function () {that.start (); };} retract this;} tesla = new car (); tesla.turnkye (); </script> </body> </html>그것은 자유 변수이므로 OnClick 이벤트의 출발은 재정의를 유발하지 않습니다.
ES6에 익숙한 경우 다음과 같이 더 간단하고 이해하기 쉬운 Fat Arrow 기호를 사용할 수 있습니다.
<! docType html> <html> <head> <meta charset = "utf-8"> <title>이 </title> </head> <body> <input type = "id ="id = "car_key"value = "test"/<script type = "text/javaScript"> car = function () {this.start = function () {console.log ( 'car starting');}; this.turnkye = function () {// var that = this; var carkey = document.getElementByid ( 'car_key'); // carkey.onclick = function () {// that.start (); //}; carkey.onclick=()=> this.start();} tesla = new car (); tesla.turnkye (); </script> </body> </html>물론, 우리는 또한 바인딩 함수 방법을 사용 하여이 문제를 해결할 수 있습니다.
<! docType html> <html> <head> <meta charset = "utf-8"> <title>이 </title> </head> <body> <input type = "id ="id = "car_key"value = "test"/<script type = "text/javaScript"> car = function () {this.start = function () {console.log ( 'car starting');}; var click = function () {this.start (); } this.turnkye = function () {// var that = that; var carkey = document.getElementByid ( 'car_key'); carkey.onclick = click.bind (this);} retract this;} tesla = new car (); tesla.turnkye (); </scrit> </html>사실, 나는 반응을 배우고 사건을 묶을 때 이러한 함정을 쓰는 방법 만 알고있었습니다. 그 당시 나는 이렇게 쓰는 방법 만 알았지 만 무슨 일이 있었는지 몰랐습니다. 오늘 나는 갑자기 깨달았다 고 느꼈다. 모든 사람에게 도움이되기를 바랍니다.