有没有比设置变量更好的方法?

时间:2010-08-25 23:58:11

标签: javascript oop callback javascript-objects

在我的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);
});

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

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

5 个答案:

答案 0 :(得分: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))
            );
        };
    };
}

查看与此相关的所有questions and answers

答案 1 :(得分:4)

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

答案 2 :(得分: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;

了解更多here

答案 3 :(得分:0)

之前我已经看到了这个模式(有问题的变量被调用了),所以我认为它确实是一个常见的javascript模式,它不仅具有更清晰的解决方案。

答案 4 :(得分:0)

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

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