简体   繁体   English

Javascript面向对象-结果变得不确定

[英]Javascript Object-Oriented - getting undedined as a result

Im making use of object-oriented capabilities of javascript program language. 我正在利用JavaScript程序语言的面向对象功能。 I have created my class LocationClass as follows: 我创建了我的类LocationClass,如下所示:

 function LocationClass(id, color, uri) {

        this.id = id;
        this.uri = uri;
        this.color = color;
        this.locations = "";
        this.Group = L.layerGroup();
        this.icon = L.MakiMarkers.icon({
            color : this.color,
            size : "l"
        });
        this.Cluster = L.markerClusterGroup();

        this.markersimple = function() {
            console.log(this.color);


            var options = {
                onSuccess : loadMarkersSuccess,
                onFailure : loadMarkersFailure,
            };

            WL.Client.invokeProcedure({
                adapter : 'Clases',
                procedure : 'getRecursos',
                parameters : [ this.uri ]
            }, options);

        };
     this.loadMarkersSuccess = function(response) {

        this.locations = response.invocationResult.results.bindings;
        console.log(this.color);
     };

     this.loadMarkersFailure = function(response) {
        alert("No se ha podido obtener la información. Revisa tu conexión.");
     }; 
    }

I'm calling the markersimple function as follows: 我正在按如下方式调用markersimple函数:

var locationclass = new LocationClass(this.id,color,vector[this.id].class.value);
locationarray.push(locationclass);

for (var i = 0; i < locationarray.length; i++) {


        locationarray[i].markersimple();


    }

The problem is that there is no object-context defined When I try to access the locationclass object within the onsuccess function. 问题是,当我尝试访问onsuccess函数中的locationclass对象时,没有定义对象上下文。 For instance, if I check the value of color, the app returns "undefined" value. 例如,如果我检查color的值,则应用程序将返回“ undefined”值。 It's the same if I try to access any function within that object. 如果我尝试访问该对象中的任何函数,则是相同的。

Any help is welcomed. 欢迎任何帮助。

You can either use bind to bind an object as the this value. 您可以使用bind将对象绑定为this值。

var options = {
    onSuccess : this.loadMarkersSuccess.bind(this),
    onFailure : this.loadMarkersFailure.bind(this),
};

Or you can use closures (from within constructor): 或者,您可以使用闭包(从构造函数内部):

var that = this;

...

this.loadMarkersSuccess = function(response) {

    that.locations = response.invocationResult.results.bindings;
    console.log(that.color);
};

By the way, functions should usually be attached to the constructor's prototype . 顺便说一句,通常应该将函数附加到构造函数的prototype

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM