1

I have a JavaScript code which I will like to clean up a bit, I was trying to pass object method name as a string but it doesn't work. Is it possible to do this?

var mywebkit = {
  execute: function(_function, _value){
    //var func = new Function(_function);
    var func = new Object(_function);
    try{
      if(Interface("android")){
        androidweb.func(_value); 
      }else if(Interface("ios")){
        webkit.messageHandlers.func.postMessage(_value);
      }
    } catch(err) {
      if(DEBUG){console.log('The native context does not exist yet', err);}
    }
  }
};

A test JavaScript object function example:

var androidweb = {
  test: function(k){
    console.log("value=" + k);
  }
};

var webkit = {
  messageHandlers: {
    test: {
      postMessage: function(k){
        console.log("value=" + k);
      }
    }
  }
};

function Interface(t){
  return (t == "android" ? true : false);
}

Usage:

mywebkit.execute("test", "This is my value");
Azametzin
  • 5,223
  • 12
  • 28
  • 46
Peter
  • 1,860
  • 2
  • 18
  • 47

1 Answers1

1

Do you mean calculated object properties like this?
If yes, you can use it with object[property] syntax.

const prop = 'test';

const foo = {
  test: () => console.log('test'),
};

foo[prop](); // logs "test"

Don't forget about validation!

const prop = 'bad';

const foo = {
  test: () => console.log('test'),
};

foo[prop](); // TypeError: foo[prop] is not a function

Validation looks like this:

if (prop in foo) {
  foo[prop]();
}

In your code try to do this

/* replace this */
 var func = new Object(_function);
 androidweb.func(_value); 
/* with this */
if (_function in androidweb) {
  androidweb[_function](_value);
}
Max Starling
  • 967
  • 8
  • 8
  • I understand you're trying to be helpful to the OP. However, this is a very common question and we should avoid multiple answers to the same question. Usually a quick note in the comments, as I did, is good enough to help guide the OP. – Ruan Mendes Mar 30 '20 at 18:40
  • @JuanMendes Okay, I see your point. I updated my answer (added my suggestion how he can resolve it :) – Max Starling Mar 30 '20 at 18:44