【问题标题】:Set object variable from inside method从内部方法设置对象变量
【发布时间】:2013-11-22 07:30:13
【问题描述】:

我被困在这个问题上,我似乎无法为创建的对象变量分配新值。见下文:

// Vesselposition class
function vessel(name,ajaxName,dataUrl,pointLimit,polylineColor,iconUrl) {
    this.name = name;
    this.ajaxName = ajaxName;
    this.dataUrl = dataUrl;
    this.pointLimit = pointLimit;
    this.polylineColor = polylineColor;
    this.iconUrl = iconUrl;

// Global variables
this.lat=0;
this.lng=0;
this.latlng;
this.dateTime, this.vesselIcon, this.marker, this.polyline, this.localTemp, this.localWindSpeed, this.localWindDir;
this.countryName, this.countryCode, this.localTime, this.localSunrise, this.localSunset, this.countryFlag;
this.localTemp, this.localWindSpeed, this.localWindDir, this.myOptions, this.ib;

// Function gets position data 
this.getData = function() {
    $.when(
        $.getJSON(this.dataUrl, { vessel: this.ajaxName, limit: this.pointLimit })

    ).done(function (data){
        this.path = [];
        // Create vessel icon for marker
        this.vesselIcon = new google.maps.MarkerImage(this.iconUrl,
            // This marker is 60 pixels wide by 58 pixels tall.
            new google.maps.Size(60, 58),
            // The origin for this image is 0,0.
            new google.maps.Point(0,0),
            // The anchor for this image is centered at 30,29 pixels.
            new google.maps.Point(30, 29)
        );

        if (data.markers.length < 1) {
            document.getElementById("map_canvas").innerHTML = "<h2>There was a problem obtaining vessel data, wait a couple of minutes and refresh your browser!</h2>";
        } else {
            for(i=0;i<data.markers.length;i++) {
                // Assign lat,lng, id, dateTime and heading
                this.lat = data.markers[i].marker.lat;
                this.lng = data.markers[i].marker.lng;

我想要完成的是在for循环中分配this.lat和this.lng坐标值。稍后,这些值应该传递给 getData 方法。

请帮助大家!在网上搜索了 3 个小时!

【问题讨论】:

    标签: javascript oop variables object set


    【解决方案1】:

    试试这个:

    //keep a reference to this
    var self = this;
    
    // Function gets position data 
    this.getData = function() {
    ....
    
       //use self here
       self.lat= 
    

    【讨论】:

    • 不走运,尝试您的建议后没有任何改变.. 无论如何谢谢! :)
    • 没人知道吗?
    • 我不明白,它应该可以工作。你把“var self = this”放在哪里了
    【解决方案2】:

    我找到了解决方案。通过使用 jQuery 的代理功能.. 我得到了它的工作。

    // Function gets position data 
    this.getData = function() {
        $.when(
        $.getJSON(this.dataUrl, { vessel: this.ajaxName, limit: this.pointLimit })
    
        ).done($.proxy(function (data){
        this.path = [];
    
        ),this}
    

    使用与第一次提供的相同的类变量。关键是在 .done 函数中使用 $.proxy 方法,范围为“this”。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多