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

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

有帮助吗?

解决方案

确保有更好的方法。它涉及创建一个具有 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))
            );
        };
    };
}

查看全部 问题与解答 与此相关。

其他提示

在处理JavaScript以存储一个参考时,实际上是一个非常普遍的模式 this 在本地变量IE中 var myThing=this;. 。请记住,功能可以访问其范围中定义的局部变量。包含功能中定义的任何变量均可访问。

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

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;

阅读更多 这里.

我以前已经看过模式(称为所讨论的变量),所以我认为这确实是一种常见的JavaScript模式,不仅具有更干净的解决方案。

我不确定这将有助于您要处理的任何情况,但是我发现Yui的自定义活动实用程序可以很好地解决此问题和关闭问题。这是一个以事件为导向的模型,也是一种略有不同的思维方式,但至少值得探索。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top