8

在我的 javascript 对象中,我发现自己在写这个:

this_object = this;

似乎这是将成员变量传递给外部函数的唯一方法......

google.maps.event.addListener(this.marker, 'click', function() {
    this.info_window.setContent('Chicago marker');
    this.info_window.open(this.map,this.marker);
});

这不起作用,我必须将对象复制到成员变量中并传递新对象(并将所有对象替换thisthis_object

这感觉很丑。有没有“更好”或“更清洁”的方式,或者这是我唯一的选择?

4

5 回答 5

5

当然有更好的方法。它涉及创建一个函数,该函数的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

这现在是 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))
            );
        };
    };
}

查看与此相关的所有关于 SO 的问题和答案。

于 2010-08-26T00:31:55.157 回答
4

在处理 JavaScript 时,将 的引用存储this在局部变量中实际上是一种非常常见的模式,即var myThing=this;. 请记住,函数可以访问在其范围内定义的局部变量。包含函数中定义的任何变量都是可访问的。

于 2010-08-26T00:03:02.903 回答
1

您会发现这段代码在许多库和项目中非常常见:

function someFunction() {
   var that = this;

   //....
}

例如,考虑这个函数:

function container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    return function () {
        if (dec()) {
            return that.member + " " + secret;
        } else {
            return null;
        }
    };
}

var c = container("foo");
alert( c() ); // "foo 2";
alert( c() ); // "foo 1";
alert( c() ); // "foo 0";
alert( c() ); // null;

在这里阅读更多。

于 2010-08-26T00:23:15.427 回答
0

我不确定这会对您处理的任何场景有所帮助,但我发现 YUI 的自定义事件实用程序可以很好地解决与此和闭包有关的范围问题。这是一个事件驱动的模型,思维方式略有不同,但至少值得探索。

http://developer.yahoo.com/yui/event/#customevent

于 2010-08-26T00:17:25.753 回答
0

我以前见过这种模式(调用了有问题的变量),所以我认为它确实是一种常见的 javascript 模式,不仅有更清洁的解决方案。

于 2010-08-26T00:03:29.763 回答