简体   繁体   中英

Calling a method on an object retrieved from Dictionary JavaScript object

I am trying to fill a Dictionary (JavaScript object) and retrieve values (custom objects/classes) from it using a string index. Then once I get the value from the dictionary, I need to invoke a method on this object. Unfortunately, that does not work because once it is being retrieved from the Dictionary, it is just a simple object ( typeof returns "object").

So the thing I'm trying to do is to cast to the object type that was initially pushed into the dictionary, which is in my case: google.visualization.Gauge . ( Reference )

I tried to use Object.create but that did not work for me. Below is my code:

var _gauges = {};

var methods = {
    init: function (options) {

        var containers = this;

        if (containers != null && containers != undefined && containers.length > 0) {
            containers.each(function (index, elem) {

                var id = $(elem).attr('id');
                var name = $(elem).data('name');
                var value = $(elem).data('value');

                var data = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            [name, value]
                ]);

                var options = {
                    width: 400, height: 120,
                    redFrom: 90, redTo: 100,
                    yellowFrom: 75, yellowTo: 90,
                    minorTicks: 5
                };
                var cont = document.getElementById(id);
                var chart = new google.visualization.Gauge(cont);
                _gauges[name] = chart;
                chart.draw(data, options);
            });
        }

    },
    setValue: function (gaugeName, newValue) {
        var thisGauge = _gauges[gaugeName];
        if (thisGauge) {
            thisGauge.setCell(0, 1, newValue);
            //var tmp = Object.create(google.visualization.Gauge, thisGauge);
            //tmp.setCell(0, 1, newValue);
        }
    }

Well, two things:

  1. If one of those "Gauge" objects is really getting put into the array correctly, when you get it back out it will emerge unscathed and you can just use it directly; no "casting" necessary.
  2. According to the documentation you linked, there is no "setCell" method :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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