문제

"이"변수를 설정하는 좋은 방법을 알 수 없다는 점을 제외하고는 JavaScript를 잘 이해하고 있습니다. 고려하다:

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body; //using body as example object
someObj.foo_variable = "hi"; //set foo_variable so it alerts

var old_fn = someObj.fn;   //store old value
someObj.fn = myFunction;   //bind to someObj so "this" keyword works
someObj.fn();              
someObj.fn = old_fn;       //restore old value

마지막 4 줄 없이이 작업을 수행 할 수있는 방법이 있습니까? 오히려 성가신 일입니다 ... 나는 익명의 기능을 묶으려고 노력했는데, 나는 아름답고 영리하다고 생각했지만 아무 소용이 없습니다.

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body;        //using body as example object
someObj.foo_variable = "hi";        //set foo_variable so it alerts
someObj.(function(){ fn(); })();    //fail.

분명히, 변수를 myfunction으로 전달하는 것은 옵션입니다 ... 그러나 그것은이 질문의 요점이 아닙니다.

감사.

도움이 되었습니까?

해결책

JavaScript의 모든 기능에 대해 정의 된 두 가지 방법이 있습니다. call(), 그리고 apply(). 함수 구문은 다음과 같습니다.

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

이러한 기능은 그들이 호출 한 함수를 호출하여 물체 매개 변수 이것.

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );

다른 팁

나는 당신이 찾고 있다고 생각합니다 call:

myFunction.call(obj, arg1, arg2, ...);

이 전화 myFunction ~와 함께 this 로 설정 obj.

약간 다른 방법도 있습니다 apply, 함수 매개 변수를 배열로 가져옵니다.

myFunction.apply(obj, [arg1, arg2, ...]);

당신이 '저장'하고 싶다면 this 나중에 완벽하게 호출 할 수 있도록 함수에 대한 가치 (예 : 더 이상 해당 값에 액세스 할 수없는 경우) bind (모든 브라우저에서 사용할 수는 없습니다) :

var bound = func.bind(someThisValue);

// ... later on, where someThisValue is not available anymore

bound(); // will call with someThisValue as 'this'

묶는 방법에 대한 나의 검색 this 여기로 데려 와서 결과를 게시하고 있습니다.

보다: https://developer.mozilla.org/en/docs/web/javascript/reference/functions/arrow_functions

대신에:

function Person() {
  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    this.age++;
  }.bind(this), 1000);
}

우리는 이제 할 수 있습니다 :

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

설정 this JavaScript의 키워드.

JavaScript에는 설정을위한 3 가지 내장 방법이 있습니다 this 키워드 편리하게. 그들은 모두에 있습니다 Function.prototype 모든 기능이 사용할 수 있도록 객체 (모든 기능은 프로토 타입 상속을 통해이 프로토 타입에서 상속되므로). 이러한 기능은 다음과 같습니다.

  1. Function.prototype.call():이 기능은 사용하려는 객체를 사용합니다. this 첫 번째 논쟁으로. 그런 다음 인수의 나머지 부분은 호출되는 함수의 해당 인수입니다.
  2. Function.prototype.apply():이 기능은 사용하려는 객체를 사용합니다. this 첫 번째 논쟁으로. 그런 다음 두 번째 인수는 함수의 인수 값을 포함하는 배열입니다 (배열의 첫 번째 요소는 함수의 첫 번째 인수이며 배열의 두 번째 인수는 함수의 두 번째 인수 등입니다.
  3. Function.prototype.bind():이 함수는 값이 다른 새 함수를 반환합니다. this. 설정하려는 객체를 this 첫 번째 인수로서의 값을 한 다음 새 함수 객체를 반환합니다.

전화/적용 및 바인딩의 차이 :

  • call 그리고 apply 사실이 비슷합니다 즉시 기능을 호출하십시오 (사전 정의 된 값 this)
  • bind 다릅니다 call 그리고 apply 이 기능이라는 사실에서 새 기능을 반환합니다 다른 바인딩으로 this 값.

예 :

const thisObj = {
  prop1: 1,
  prop2: 2,
};

function myFunc(arg1, arg2) {
  console.log(this.prop1, this.prop2);
  console.log(arg1, arg2);
}

// first arg this obj, other arguments are the  
// respective arguments of the function
myFunc.call(thisObj, 'Call_arg1', 'Call_arg2');

// first arg this obj, other argument is an array which  
// are the respective arguments of the function
myFunc.apply(thisObj, ['Apply_arg1', 'Apply_arg2']);


// the bind method returns a new function with a different
// this context which is stored in the newMyFunc variable
const newMyFunc = myFunc.bind(thisObj);

// now we can call the function like a normal function 
newMyFunc('first', 'second');

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top