"이"변수를 쉽게 설정합니까?
-
19-08-2019 - |
문제
"이"변수를 설정하는 좋은 방법을 알 수 없다는 점을 제외하고는 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으로 전달하는 것은 옵션입니다 ... 그러나 그것은이 질문의 요점이 아닙니다.
감사.
다른 팁
당신이 '저장'하고 싶다면 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
모든 기능이 사용할 수 있도록 객체 (모든 기능은 프로토 타입 상속을 통해이 프로토 타입에서 상속되므로). 이러한 기능은 다음과 같습니다.
Function.prototype.call()
:이 기능은 사용하려는 객체를 사용합니다.this
첫 번째 논쟁으로. 그런 다음 인수의 나머지 부분은 호출되는 함수의 해당 인수입니다.Function.prototype.apply()
:이 기능은 사용하려는 객체를 사용합니다.this
첫 번째 논쟁으로. 그런 다음 두 번째 인수는 함수의 인수 값을 포함하는 배열입니다 (배열의 첫 번째 요소는 함수의 첫 번째 인수이며 배열의 두 번째 인수는 함수의 두 번째 인수 등입니다.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');
제휴하지 않습니다 StackOverflow