4

I’m making a JavaScript object with literal notation, but I’m not sure how to make the object receive parameters 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 why I want that is because I want people to be able to skip the title and just put the body, and do the same for many other parameters.

So that’s why I need something like how we can use jQuery functions’ parameters {parameter:"yay", parameter:"nice"}

P.S. I’m open too for modification of the current method – keeping in mind that there would be many parameters, some required and some optional, and which cannot be ordered in a specific way.

3 Answers 3

6

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

var hi = {
  say: function(obj) {
    alert(obj.title + "\n" + obj.body);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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."
});

Comments

0
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
     // ...
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.