简体   繁体   中英

How can I call a function stored in one object on another object by name?

In the below, options.min==1969 . Id like to make a new date using options.min then call one of the following date functions on that date .getFullYear(), .getMonth(), .getDay(), .getHours(), .getMinutes() .

Which function gets called on the new date should depend on the value of options.type

I'd like to do this as concisely as possible and avoid repetitive code in if and switch statements.

THis is my attempt to make this work:

  var options = { dateFunctions: { years: "getFullYear", months: "getMonth", days: "getDate", hours: "getHours", minutes: "getMinutes" }, type: 'days', min: '1969-01-02 10:00:00' }; console.log('before: ' + options.min); options.min = new Date(options.min)[options.dateFunctions[options.type]] console.log('after: ' + options.min); 

I expect calling options.min = new Date(options.min)[options.dateFunctions[options.type]] to be equivalent to calling new Date('1969-01-02 10:00:00').getDate()) and for options.min to be set to 1 .

Instead, options.min is set to function getDate() { [native code] }

What do I need to change to get the result of the function called on options.min instead of the function itself?

The function was not called:
Try the direct way:

options.min = new Date(options.min)[options.dateFunctions[options.type]]();

or via call method

Date.prototype[options.dateFunctions[options.type]].call(new Date(options.min));

There are two ways to access properties in an object . Dot notation and Bracket notation. You're probably looking for the latter.

val = object[function_name]();

Ie Just add the parentheses at the end to call the function after you access it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM