2016-07-01 31 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')

可與代理來也做了更有效的。