Mudassir Ali
Mudassir Ali

Reputation: 8041

Dynamically calling a property's method

Okay see the following code:

function person(name){
    this.name = name;
    this.say = function(){
        alert(this.name);
    }
};

Main = {};

Main.person1 =  new person("p1");

Main.person2 =  new person("p2");

Main.person3 =  new person("p3");

executeSay = function(argument1){
 //Implementation
}

What executeSay should do is, call the say method of the given argument, I am not sure how it goes but let me put this way executeSay("person1") should execute Main.person1.say() and so on. I think we can accomplish this by call method but I am not sure about the implementation.

Please don't suggest the following approach

say = function(){
  alert(this.name);
}
say.call(Main.person1);

Upvotes: 1

Views: 69

Answers (4)

strandel
strandel

Reputation: 21

I'd do it like this:

function Person(name){
  this.name = name
}

Person.prototype.say = function () {alert(this.name)}

var main = {
  person1: new Person('p1')
, person2: new Person('p2')
, person3: new Person('p3')
}

function executeSay(personStr) {main[personStr].say()}

(Updated to reflect the the string parameter for executeSay)

Upvotes: 2

spicavigo
spicavigo

Reputation: 4224

Is this not working?

executeSay = function(person){person.say()}

Upvotes: 0

Alberto De Caro
Alberto De Caro

Reputation: 5213

Let executeSay calls the say method on the argument object:

executeSay = function(person){
 person.say();
}

Demo.

Upvotes: 0

Sirko
Sirko

Reputation: 74076

If you already pass the object in the function, you can access all its methods there, so use:

executeSay = function(person){
  person.say();
}

and then call this function by, e.g.,

executeSay( Main.person1 );

Upvotes: 2

Related Questions