简体   繁体   中英

Javascript - define object in function with arguments

I am building a large object which will eventually be processed by a separate library. There are repeating structural elements in the object which take different parameters, so I was hoping to write a function that would let me automate the process a little.

function addTable(headline) {
    var table = { header: headline, ... }
}

But I get an error when I try to access the function arguments in the object. That is, I can't use headline in the object. How can I access these parameters? Or is this the wrong approach?

UPDATE:

It looks like this is a problem with the library that processes the object, but something else is strange. If I do this:

var table = { header: ""+headline+"" ... }

It WORKS. But I don't get it. headline and ""+headline+"" are both strings. What could possibly be the difference between a string that starts and ends with empty quotes, and one that doesn't?

You should be able to access them "if they are passed into the method", but undefined can also be passed in from the caller.

Use the F12 tools to inspect the arguments and the callstack

function addTable(headline) {
    // headline is undefined if its not passed
    // headline can also be passed in as null or undefined
    // headline == arguments[0];
    // if nothing is passed then arguments.length should equal 0
    // add a F12 breakpoint and inspect all arguments and the callstack
    var table = { header: headline, ... }
}

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