从方法内部设置对象变量

Set object variable from inside method

本文关键字:对象 变量 设置 内部 方法      更新时间:2023-09-26

我陷入了这个问题,似乎无法为创建的对象变量分配新值。见下文:

// 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.lang分配坐标值。稍后,应该将这些值传递给getData方法。

请帮帮伙计们!已经在网上搜索了3个小时了!

试试这个:

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

我找到了一个解决方案。通过使用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}

使用与第一次提供的类变量相同。。关键是在作用域为"this"的.done函数中使用$.proxy方法。