質問

私は 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 に渡すことはオプションです...しかしそれはこの質問の要点ではありません。

ありがとう。

役に立ちましたか?

解決

JavaScript のすべての関数に対して 2 つのメソッドが定義されています。 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に設定thisobj呼び出します。

少し異なる方法 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をバインドする方法についての私の検索はここで私をもたらした:「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 オブジェクトについては機能を利用することができ(すべての機能を継承この試作を経由のに必要な継承).これらの機能は次の通りである:

  1. Function.prototype.call():この関数はオブジェクトとして利用する this としての最初の引数。その後、残りの引数は、それぞれの引数に関数が呼び出されます。
  2. Function.prototype.apply():この関数はオブジェクトとして利用する this としての最初の引数。そして二つ目の引数が配列を含むの価値を引数の関数と呼ばれる(最初の要素の配列が最初の引数の機能、第二引数の配列は、第二引数の機能ます。
  3. Function.prototype.bind():この機能を返します新しい機能が異なる値 this.このオブジェクト設定をしたいとして this としての価値を最初の引数として返します新しい関数オブジェクトです。

違い電話が応募と結合する:

  • callapply 類似するという事実に 直ちに、機能 (定義済みの値 this)
  • bind が異なるから callapply ということでこの機能 新たに追加された機能 異なる結合の 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