「この」変数を簡単に設定しますか?
-
19-08-2019 - |
質問
私は Javascript についてはかなり理解していますが、「this」変数を設定する良い方法がわかりません。考慮する:
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
をバインドする方法についての私の検索はここで私をもたらした:「2015年のECMAScript」は、我々はまた、辞書的に矢印の機能を使用してこれを設定することができます。
を参照してください: https://developer.mozilla.org/ EN /ドキュメント/ウェブ/ JavaScriptを/リファレンス/関数/ 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は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