Gal*_*len 8 javascript oop callback javascript-objects
在我的javascript对象中,我发现自己写了这个:
this_object = this;
Run Code Online (Sandbox Code Playgroud)
看来这是将成员变量传递给外部函数的唯一方法......
google.maps.event.addListener(this.marker, 'click', function() {
this.info_window.setContent('Chicago marker');
this.info_window.open(this.map,this.marker);
});
Run Code Online (Sandbox Code Playgroud)
这是不行的,我有对象复制到一个成员变量,并通过新的对象(和替换所有this带this_object)
这感觉很难看.是否有"更好"或"更清洁"的方式,或者这是我唯一的选择?
当然有一个更好的方法.它涉及创建一个具有this已绑定到特定对象的上下文的函数.
要让this上下文引用当前对象,请bind()在函数上调用方法并将所需的上下文作为参数传递.
google.maps.event.addListener(this.marker, 'click', function() {
this.info_window.setContent('Chicago marker');
this.info_window.open(this.map,this.marker);
}.bind(this)); // <-- notice we're calling bind() on the function itself
Run Code Online (Sandbox Code Playgroud)
现在这是ECMAScript标准的一部分,如果浏览器本身没有实现它,那么很容易就可以自己实现.
if (!Function.prototype.bind) {
Function.prototype.bind = function () {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(
object, args.concat(Array.prototype.slice.call(arguments))
);
};
};
}
Run Code Online (Sandbox Code Playgroud)
查看与此相关的所有问题和答案.