[javascript] var self = this?

이벤트 핸들러에 대한 콜백의 범위 변경으로 인스턴스 메소드를 사용 this에서 “내 예”“바로 콜백이라고 무엇이든을” . 내 코드는 다음과 같습니다

function MyObject() {
  this.doSomething = function() {
    ...
  }

  var self = this
  $('#foobar').bind('click', function(){
    self.doSomethng()
    // this.doSomething() would not work here
  })
}

작동하지만 이것이 최선의 방법입니까? 나에게 이상해 보인다.



답변

이 질문은 jQuery에만 국한된 것이 아니라 일반적으로 JavaScript에만 해당됩니다. 핵심 문제는 임베디드 함수에서 변수를 “채널 화”하는 방법입니다. 이것은 예입니다 :

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

이 기술은 클로저를 사용합니다. 그러나 그것은 작동하지 this않기 때문에this 범위에서 범위로 동적으로 변경 될 수있는 의사 변수 .

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

우리는 무엇을 할 수 있습니까? 변수에 할당하고 별명을 통해 사용하십시오.

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this이와 관련하여 고유하지 않습니다 arguments. 앨리어싱 (aliasing)으로 같은 방식으로 처리해야하는 다른 의사 변수입니다.


답변

예, 이것은 일반적인 표준으로 보입니다. 일부 코더는 자기를 사용하고 다른 코더는 나를 사용합니다. 이벤트와 달리 “실제”객체에 대한 참조로 사용됩니다.

실제로 얻는 데 시간이 조금 걸렸습니다. 처음에는 이상하게 보입니다.

나는 보통 내 객체의 맨 위에서 이것을 수행합니다 (데모 코드는 실례합니다-다른 것보다 더 개념적이며 우수한 코딩 기술에 대한 교훈은 아닙니다) :

function MyObject(){
  var me = this;

  //Events
  Click = onClick; //Allows user to override onClick event with their own

  //Event Handlers
  onClick = function(args){
    me.MyProperty = args; //Reference me, referencing this refers to onClick
    ...
    //Do other stuff
  }
}


답변

var functionX = function() {
  var self = this;
  var functionY = function(y) {
    // If we call "this" in here, we get a reference to functionY,
    // but if we call "self" (defined earlier), we get a reference to function X.
  }
}

편집 : 개체 내에서 중첩 함수는 주변 개체가 아닌 전역 창 개체를 사용합니다.


답변

ES2015 또는 유형 스크립트 및 ES5를 수행하는 경우 코드에서 화살표 기능을 사용할 수 있으며 해당 오류가 발생하지 않으며 인스턴스에서 원하는 범위를 나타냅니다.

this.name = 'test'
myObject.doSomething(data => {
  console.log(this.name)  // this should print out 'test'
});


답변

이것에 대한 한 가지 해결책은 모든 콜백을 자바 스크립트로 객체에 바인딩하는 것입니다. bind 메소드 입니다.

명명 된 방법으로이 작업을 수행 할 수 있습니다.

function MyNamedMethod() {
  // You can now call methods on "this" here 
}

doCallBack(MyNamedMethod.bind(this)); 

또는 익명 콜백

doCallBack(function () {
  // You can now call methods on "this" here
}.bind(this));

의지하는 대신 이것들을하는 var self = this것은this 자바 스크립트에서 동작하는지 하고 클로저 참조에 의존하지 않는 .

또한 ES6의 팻 화살표 연산자는 기본적으로 .bind(this)익명 함수를 호출하는 것과 같습니다.

doCallback( () => {
  // You can reference "this" here now
});


답변

jQuery를 사용하지는 않았지만 프로토 타입과 같은 라이브러리에서 함수를 특정 범위에 바인딩 할 수 있습니다. 이를 염두에두고 코드는 다음과 같습니다.

 $('#foobar').ready('click', this.doSomething.bind(this));

bind 메소드는 지정한 범위로 원래 메소드를 호출하는 새 함수를 리턴합니다.


답변

ES6에서는 화살표 기능으로 인해 this값 을 캡처하기 때문에이 작업을 수행 할 필요가 없습니다 .