简体   繁体   中英

How do I get the arguments passed to a function that is a property of an object?

I have an object that has a property which is a function:

Example:

const obj = {func: function() {console.log('I am a function in an object')}};

When I call this function, I would call it by obj.func() . If I wanted to pass more arguments to this function, how can I access them? I've tried:

const obj = {
  func: function() {
    const args = [...arguments];
    console.log(args);
  }
}

so when I call obj.func(arg1, arg2) , I expect it to log what arg1 and arg2 is but this call returns the obj as the single argument. I have not found any other answer about this. BTW, I'm new to javascript.

Just paste it as a value...

 const obj = { func: function() { const args = [...arguments]; console.log(args); } } obj.func("value1","value2")
or like this
 const obj = { func: function(arg1,arg2) { const args = [arg1,arg2]; console.log(args); } } obj.func("value1","value2")

 const obj = { func: function() { const args = [arguments[0],arguments[1]]; console.log(args); } } obj.func("value1","value2")

Just use a loop and arguments to straight away access your function arguments. Here's an alteration to your function:

const obj = {
  func: function() {
    for (var iteration=0; iteration<arguments.length; iteration++) 
      console.log(arguments[iteration]);
  }
}

An even easier option that does not need the arguments variable would be the following:

 const obj = { func: (...args) => { console.log(args); } }; obj.func("value1", "value2");

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