简体   繁体   English

使用文字符号制作JavaScript对象

[英]Making a JavaScript object using literal notation

I'm making a JavaScript object with literal notation, but I'm not sure how to make the object receive parameters like this: 我正在用文字符号制作一个JavaScript对象,但不确定如何使该对象接收如下参数:

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

instead of hi.say("foo", "bar"); 而不是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"} 因此,这就是为什么我需要类似如何使用jQuery函数的参数{parameter:"yay", parameter:"nice"}

PS 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. PS我也愿意修改当前方法-请记住,会有很多参数,其中一些是必需的,一些是可选的,并且不能以特定的方式进行排序。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM