Pass object to javascript function

前端 未结 4 405
独厮守ぢ
独厮守ぢ 2020-12-08 02:22

I have recently been messing around with jQuery on my website, and I have a fairly limited knowledge of Javascript. I am beginning to like the jQuery ability to pass variabl

相关标签:
4条回答
  • 2020-12-08 02:28
    function myFunction(arg) {
        alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
    }
    
    myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });
    
    0 讨论(0)
  • 2020-12-08 02:29

    The "braces" are making an object literal, i.e. they create an object. It is one argument.

    Example:

    function someFunc(arg) {
        alert(arg.foo);
        alert(arg.bar);
    }
    
    someFunc({foo: "This", bar: "works!"});
    

    the object can be created beforehand as well:

    var someObject = {
        foo: "This", 
        bar: "works!"
    };
    
    someFunc(someObject);
    

    I recommend to read the MDN JavaScript Guide - Working with Objects.

    0 讨论(0)
  • 2020-12-08 02:48

    Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

    If using ES6:

        function yourFunction(args){
            let defaults = {opt1: true, opt2: 'something'};
            let params = {...defaults, ...args}; // right-most object overwrites 
            console.log(params.opt1);
        }
    

    Older Browsers using Object.assign(target, source):

        function yourFunction(args){
            var defaults = {opt1: true, opt2: 'something'};
            var params = Object.assign(defaults, args) // args overwrites as it is source
            console.log(params.opt1);
        }
    
    0 讨论(0)
  • 2020-12-08 02:52

    when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

    0 讨论(0)
提交回复
热议问题