在 Javascript 中实例化对象时,我想启用以下场景:
- 该对象可以在没有任何参数的情况下实例化,并使用默认属性值创建
- 可以使用为对象属性设置初始值的参数来实例化该对象
解决方案应该:
- 不分配尚未在对象上定义的属性
- 允许设置任意数量的属性(无、部分或全部)
- 易于应用于脚本定义的任何对象,这意味着我们事先不知道可以设置哪些属性。
jQuery 可供使用,但欢迎使用纯 JS 解决方案。
采用以下对象构造函数:
function User() {
this.name = null;
this.email = null;
this.password = null;
}
该解决方案应该允许我实现以下目标:
new User();
// User { name: null, email: null, password: null }
new User(<parameter(s) that specify a value for name, email and password>);
// User { name: "passed value", email: "passed value", password: "passed value" }
new User(<parameter that specifies a value for name>);
// User { name: "passed value", email: null, password: null }
new User(<parameter(s) that specify values for name and non-existent property age>);
// User { name: "passed value", email: null, password: null }
最佳答案
组合$.extend()
使用默认对象使这变得非常容易:
function User(options) {
var defaults = {
name: null,
email: null,
password: null
};
var options = $.extend({}, defaults, options);
console.log(options);
}
new User();
// null, null, null
new User({name : 'First'});
// First, null, null
new User({name : 'First', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9feaecfaedecb1f1fef2fadfeaecfaedecb2faf2fef6f3b1fcf0f2" rel="noreferrer noopener nofollow">[email protected]</a>'});
// First, <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4237312730316c2c232f270237312730316f272f232b2e6c212d2f" rel="noreferrer noopener nofollow">[email protected]</a>, null
new User({name : 'First', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3346405641401d5d525e567346405641401e565e525a5f1d505c5e5e" rel="noreferrer noopener nofollow">[email protected]</a>', password : 'password1'});
// First, <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="186d6b7d6a6b367679757d586d6b7d6a6b357d75797174367b7775" rel="noreferrer noopener nofollow">[email protected]</a>, password1
这里正在工作:http://jsfiddle.net/m6KQC/2/
如果您不想添加调用函数时传递的额外属性,则只需使用下面的代码而不是 $.extend()
。这与您的原始函数具有相同的功能:
function setObjectProperties(defaults, options, target) {
var options = options || {};
for (var prop in defaults) {
target[prop] = (typeof options[prop] === "undefined") ? defaults[prop] : options[prop];
}
}
您可以将其包装在原始函数中并像这样使用它:
setObjectProperties(defaults, options, this);
您可以在这里看到此替代方案:http://jsfiddle.net/m6KQC/9/
关于javascript - 从构造上的参数设置任意对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365395/