Pass object to javascript function

前端 未结 4 414
独厮守ぢ
独厮守ぢ 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: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);
        }
    

提交回复
热议问题