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

如何从方法内的回调函数访问对象属性?

  •  0
  • Toto  · 技术社区  · 15 年前

    我正在定义这个类:

    function GMap(map, marker, geocoder) {
        this.map = map;
        this.marker = marker;
        this.geocoder = geocoder;
    
        this.setMarker = function(address) {
            this.geocoder.geocode({'address' : address}, function(results, status) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
            });
        }
    }
    

    如何访问 map marker 来自回调函数的gmap属性?

    谢谢。

    4 回复  |  直到 12 年前
        1
  •  5
  •   Kevin Vaughan    15 年前

    函数对象原型有一个“apply”方法,您可以使用该方法在函数中设置“this”的上下文。检查api/code中的geocoder.code是什么,许多库都会通过一个额外的参数来处理这个问题,即:

    this.someObj.someFn(params, callback, scope);
    

    在somefn中,它将使用类似于以下内容的回调:

    callback.apply(scope || window, [callbackArg1, callbackArg2]);
    

    这将使“callback”中的“this”上下文成为“scope”,或者如果没有传入任何内容,“this”将成为窗口的全局上下文。一些JavaScript库还提供了一种创建回调函数委托的方法,以确保无论从何处调用函数,始终以预期的范围调用函数。一个例子是 ExtJS's Function.createDelegate

    如果您使用的库没有提供这个内置功能,那么您可以在回调闭包中创建一个本地var来引用,即:

    this.setMarker = function(address) {
        var thisGMap = this;
        this.geocoder.geocode({'address' : address}, function(results, status) {
            thisGMap.map.setCenter(results[0].geometry.location);
            thisGMap.marker.setPosition(results[0].geometry.location);
        });
    }
    
        2
  •  1
  •   BGerrissen    15 年前

    这就是你要找的吗?

    function GMap(map, marker, geocoder) {
        this.map = map;
        this.marker = marker;
        this.geocoder = geocoder;
    
        var currentGMap = this; // private variable bound to GMap constructor scope
    
        this.setMarker = function(address) {
            this.geocoder.geocode({'address' : address}, function(results, status) {
                // currentGMap is available (yay closures)
                currentGMap.map.setCenter(results[0].geometry.location);
                currentGMap.marker.setPosition(results[0].geometry.location);
            });
        }
    }
    

    注意:map和marker也通过一个闭包绑定,不过我假设您希望在创建GMAP实例之后能够更改map和marker属性。

    编辑:是的,我看到凯文在他的遮阳篷的最后一部分也在我面前展示了这个。

        3
  •  0
  •   Thomas Clayson    15 年前

    我猜是谷歌地图?你为什么要穿过地图和记号笔?使它们成为全局变量(即:Put var map; 在所有功能之外)那么您应该能够从任何地方访问它们。

    在函数中重用变量名也是一个坏主意。如果您首先将它们传递到函数中,那么它们将成为函数变量,因此在函数中定义map、marker和geocoder是毫无意义的,因为您已经能够使用map、marker和geocoder访问它们了。:)

        4
  •  0
  •   Daniel Loureiro    12 年前

    如果您使用jquery,有一个方法 $.proxy() 可用于更改上下文(将函数的“this”设置为任意值)。

    this.setMarker = function(address) {
        this.geocoder.geocode({'address' : address}, $.proxy(function(results, status) {
            this.map.setCenter(results[0].geometry.location);
            this.marker.setPosition(results[0].geometry.location);
        }, this));
    }