从inside方法设置对象变量

时间:2013-11-22 07:30:14

标签: javascript oop variables object set

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

// 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个小时!

2 个答案:

答案 0 :(得分:0)

试试这个:

//keep a reference to this
var self = this;

// Function gets position data 
this.getData = function() {
....

   //use self here
   self.lat= 

答案 1 :(得分:0)

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