代码之家  ›  专栏  ›  技术社区  ›  Galen

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

  •  8
  • Galen  · 技术社区  · 14 年前

    在我的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 回复  |  直到 14 年前
        1
  •  5
  •   Anurag    14 年前

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

        2
  •  4
  •   gnarf    14 年前

    在处理JavaScript以存储 this 在局部变量中,即。 var myThing=this; . 记住函数可以访问在其作用域中定义的局部变量。包含函数中定义的任何变量都可以访问。

        3
  •  1
  •   Yanick Rochon    14 年前

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

    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

        4
  •  0
  •   Jasper    14 年前

    我以前见过这种模式(调用了所讨论的变量),所以我假设它确实是一种常见的javascript模式,而不仅仅是一种更干净的解决方案。

        5
  •  0
  •   JeremyWeir    14 年前

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

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