调用在函数内创建的Object中的方法

时间:2017-11-15 04:41:09

标签: javascript function object methods

我对这个问题很困惑,甚至JavaScript MDN都没有为我澄清这个概念。

有一个名为invokeMethod的函数,在该函数中我必须创建一个Object。对象包括方法。我需要使用括号表示法调用Object中的Method,但不需要返回任何内容。

这是问题和我的代码。当我尝试在函数括号中调用该方法时,我不断收到错误消息。

问题:method是一个字符串,其中包含对象上方法的名称 使用括号表示法调用此方法。 什么都不需要退货。

输入示例:

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

我的代码:

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

invokeMethod(obj[foo]);

2 个答案:

答案 0 :(得分:1)

检查是否有这个帮助。



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");




***如果要将对象本身作为参数传递:



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




答案 1 :(得分:0)

也许这可能有所帮助。

看看你的功能我看到你有两个元素package proj3; import java.util.Scanner; import java.util.Random; /** * <p> Title: Project 4: The Project4App Class </p> * <p> Description: Creates an math game for children </p> * @author Justin Abeles */ public class Project4App { /** * <p> Name: main method </p> * * @param args values to be sent to the method */ public static void main(String args[]){ int addCorrect = 0; int addWrong = 0; int subCorrect = 0; int subWrong = 0; while(true){ Question quiz = new Question(); Scanner scan = new Scanner(System.in); System.out.println("What is the result?\n" + quiz.toString()); int age = scan.nextInt(); int answer = quiz.determineAnswer(); char operator = quiz.getOperator(); if(age == answer && operator == '+') System.out.println("Congratulations, you got it correct!"); if((age == answer) && (operator == '-')) System.out.println("Congratulations, you got it correct!"); if((age != answer) && (operator == '+')) System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer()); if((age != answer) && (operator == '-')) System.out.println("The correct answer for " + quiz.toString() + " is " + quiz.determineAnswer()); if(age == answer && operator == '+') addCorrect = addCorrect + 1; else if(age == answer && operator == '-') subCorrect = subCorrect + 1; else if(age != answer && operator == '+') addWrong = addWrong + 1; else subWrong = subWrong + 1; scan.close(); } } object作为参数。所以,你的功能很糟糕

method

如果你要收到function invokeMethod(object, method) { // code here const obj = { name: 'kung', foo: function(){ console.log('foo'); } }; } ,那么你应该有这个,

obj-function

现在,按照你的例子,我会认为你真的想收到function invokeMethod(method) 。那么,在这种情况下,你应该这样做。

obj-function