Creating a JavaScript Object Using a Literal

Im creates a JavaScript object with literal notation, but Im not sure how to make the parameters for getting the object like this:

hi.say({title: "foo", body: "bar"}); 

instead of hi.say("foo", "bar"); .

Current code:

 var hi = { say: function (title, body) { alert(title + "\n" + body); } }; 

The reason I want it is because I want people to be able to skip the header and just put the body in and do the same for many other parameters.

That's why I need something like how we can use jQuery function {parameter:"yay", parameter:"nice"}

PS Im also open to modify the current method - bearing in mind that there will be many parameters, some are required and some are optional, and which cannot be ordered in a certain way.

+4
source share
3 answers

There is no special parameter syntax for this, just make the function a single parameter, and this will be the object:

 var hi = { say: function(obj) { alert(obj.title + "\n" + obj.body); } } 
+6
source

Something like this should work:

 var hi = { say: function(options) { if (options.title) alert(options.title + "\n" + options.body); else alert('you forgot the title!'); } } hi.say({ //alerts title and body "title": "I'm a title", "body": "I'm the body" }); hi.say({ //alerts you for got the title! "body": "I'm the body." }); 
+1
source
 var hi = { say: function( opts ) { var title = (opts.title)?opts.title:"default title"; var body = (opts.body)?opts.body:"default body"; // do whatever with `body` and `title` just like before // ... } }; 
0
source

All Articles