babycoder
babycoder

Reputation: 180

Invoke a method in an Object that was created inside a function

I am confused by this question and not even the JavaScript MDN is clarifying the concept for me.

There is a function called invokeMethod and in that function I have to create an Object. The Object includes a Method. I need to invoke the Method in the Object using bracket notation but nothing needs to be returned.

Here is the Question and my code. I keep getting error messages when I try to call the method in the function parentheses.

Question: method is a string that contains the name of a method on the object Invoke this method using bracket notation. Nothing needs to be returned.

Input Example:

{ foo: function() {} }, 'foo'

My code:

function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}

invokeMethod(obj[foo]);

Upvotes: 0

Views: 1762

Answers (2)

Akash Shrivastava
Akash Shrivastava

Reputation: 1365

Check if this help.

function invokeMethod(object, method) {
  // object definitions
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };

  // conditional invokation 
  switch(object){
    case "obj":
      if(typeof obj[method] == "function") return obj[method]();
    default:
      console.log("Given object not found!");
    }  
}
// call method
invokeMethod("obj", "foo");

***If the object itself is to be passed as parameter:

function invokeMethod(object, method) {
	if(typeof object[method] === "function")	
		object[method]();
	else
		console.log('Invalid function name!');
  }
  
  invokeMethod({ foo: function() {console.log('foo');} }, 'foo');

Upvotes: 1

Kenry Sanchez
Kenry Sanchez

Reputation: 1743

Maybe this could help.

Look at your function I'm seen that you have as arguments two elements object and method. So, your functions it's bad doing this

function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}

if you are going to receive the obj-function, you should have just this,

function invokeMethod(method)

Now, Following your example, I'm going to think that you really want to receive the obj-function. So, in that case, you should do this.

const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };

function invokeMethod(obj, method) {
  if((method in obj) && typeof obj[method] ==="function"){

    return obj[method]();
  }
}

invokeMethod(obj, 'foo');

Upvotes: 0

Related Questions