使用文字符号创建JavaScript对象
我正在使用文字符号创建一个JavaScript对象,但我不确定如何使该对象接收如下参数:使用文字符号创建JavaScript对象,javascript,syntax,Javascript,Syntax,我正在使用文字符号创建一个JavaScript对象,但我不确定如何使该对象接收如下参数: hi.say({title: "foo", body: "bar"}); 而不是hi.say(“foo”,“bar”) 当前代码: var hi = { say: function (title, body) { alert(title + "\n" + body); } }; 我之所以希望这样做,是因为我希望人们能够跳过标题,只放置正文,并对许多其他参数执行相同的操作
hi.say({title: "foo", body: "bar"});
而不是hi.say(“foo”,“bar”)代码>
当前代码:
var hi = {
say: function (title, body) {
alert(title + "\n" + body);
}
};
我之所以希望这样做,是因为我希望人们能够跳过标题,只放置正文,并对许多其他参数执行相同的操作
这就是为什么我需要一些东西,比如如何使用jQuery函数的参数{parameter:“yay”,parameter:“nice”}
另外,我对修改当前方法也持开放态度–请记住,会有许多参数,有些是必需的,有些是可选的,不能以特定的方式排序。没有特殊的参数语法,只需使函数采用单个参数,这将是一个对象:
var hi = {
say: function(obj) {
alert(obj.title + "\n" + obj.body);
}
}
像这样的方法应该会奏效:
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(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."
});