Javascript JS:get runtime';这';从外部功能
Javascript JS:get runtime';这';从外部功能,javascript,Javascript,函数中的此在运行时设置: 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 misteryF
函数中的此
在运行时设置:
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
不是现成的(javascript不是python)。一种方法是创建对象的副本,并将所有方法绑定到该副本:
var boundObject=函数(obj){
var res={};
Object.keys(obj.forEach)(函数(k){
var x=obj[k];
if(x.bind)
x=x.bind(obj);
res[k]=x;
});
返回res;
}
//
var person={
名字:'乔',
你好:功能(东西){
log(this.name+“说你好”+东西);
}
}
helloJoe=boundObject(person);
helloJoe('there')
此
动态绑定到调用方法的对象。这意味着,只要您的misteryFunction
没有通过apply
、call
或绑定bind
调用,您就无法确定它的接收者。