this
在运行时设置:
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
答案 0 :(得分: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')

也可以使用代理更有效地完成。