2016-07-01 9 views
1

thisから:JS:ランタイムを取得し「この」実行時に設定されている関数内の外側の関数

var person = { 
    hello: function(thing) { 
    console.log(this, " says hello " + thing); 
    } 
} 

// the code: 
person.hello("world"); 

// is equivalent to: 
person.hello.call(person, "world"); 

がいることを取得するには、(オブジェクト)にバインドさ関数への参照から始めて、それが可能ですオブジェクト?何かのように:

var misteryFunction = person.hello; 
misteryFunction.getMyRuntimeThis() // returns: person 
+1

'this'はメソッドが呼び出されるオブジェクトに動的にバインドされます。これは、 'misteryFunction'が' apply'、 'call'または' bind'でバインドされていない限り、それが受信者であると判断できないことを意味します。 – ftor

答えて

2

(javascriptはPythonではありません)一つの方法は、それに結合されたすべてのメソッドを持つオブジェクトのコピーを作成することです:

var boundObject = function(obj) { 
 
    var res = {}; 
 
    Object.keys(obj).forEach(function(k) { 
 
    var x = obj[k]; 
 
    if(x.bind) 
 
     x = x.bind(obj); 
 
    res[k] = x; 
 
    }); 
 
    return res; 
 
} 
 

 
// 
 

 
var person = { 
 
    name: 'Joe', 
 
    hello: function(thing) { 
 
    console.log(this.name + " says hello " + thing); 
 
    } 
 
} 
 

 
helloJoe = boundObject(person).hello; 
 
helloJoe('there')

もプロキシをより効率的に行うことができます。

関連する問題