0

I was working on a javascript template that our UI developers can use. But I couldn't find a way to get rid of eval. Can someone show me a way to replace eval?

/*jslint browser:true, passfail:false, sloppy:true, indent:4, maxerr:1000*/
/*global  $*/

var Main = {
    Init: function () {    
        this.Helper.Import("Main.Sliders");
    },

    Helper: {
        Import: function (classname) {
            var objectToInit = eval(classname);
            objectToInit.Init();
        },

        UserAgent: {
            IsIphone: navigator.userAgent.match(/iPhone|iPod/i) !== null,
            IsIos: navigator.userAgent.match(/iPhone|iPad|iPod/i) !== null,
            IsAndroid: navigator.userAgent.match(/Android/i) !== null
        }
    },

    Sliders: {
        Init: function () {
            alert('dada');
        }
    }
};

$(document).ready(function () {
    Main.Init();
});
erdost
  • 3
  • 2
  • insert `console.log(classname)` before the eval line, run it a few times, and tell us what is being logged – Paul Nov 17 '14 at 07:41
  • Unrelated but $.browser has been deprecated since jQuery 1.3 and was removed in 1.9 http://api.jquery.com/jquery.browser/ – Pete TNT Nov 17 '14 at 07:42
  • possible duplicate of [Instantiate a JavaScript Object Using a String to Define the Class Name](http://stackoverflow.com/questions/1366127/instantiate-a-javascript-object-using-a-string-to-define-the-class-name) – Abhitalks Nov 17 '14 at 07:45
  • @PeteTNT thank you. I took out $.browser lines. – erdost Nov 17 '14 at 08:15

2 Answers2

0

var Main = {
    Init: function () {    
        this.Helper.Import("Main.Sliders");
   },

    Helper: {
        Import: function (classname) {
            var trail = classname.split('.');
            var current = window;
            while ((subobj = trail.shift())) {
              current = current[subobj];
            }
            current.Init();
        },
    },

    Sliders: {
        Init: function () {
            alert('dada');
        }
    }
};

Main.Init();

However, it would be easier to just do Main.Sliders.Init(). Is there a particular reason why you would need the object name to be in a string?

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

In javascript doesn't exist dynamic variables buy dynamic properties does.

Import: function (classname) {
            var arr = classname.split('.'),
                length = arr.length,
                objectToInit = /*current context of the variable Main*/,
                tmp = objectToInit,
                i = 0;
            while(i < length) {
                tmp = tmp[arr[i]]; 
                i++;
            }
            tmp.Init();
        }
ariel_556
  • 368
  • 1
  • 9