ors*_*har 43 javascript constructor overriding
我能做点什么吗?:
function User(form) {
this._username = form.username.value;
this._password = form.password.value;
this._surname = form.surname.value;
this._lastname = form.lastname.value;
this._birthdate = form.b_day.value+"-"+form.b_month.value+"-"+form.b_year.value;
this._avatar = form.avatar;
this._messages = new Array();
this._messagesCount=0;
}
function User(userName,password,surname,lastName,birthdate) {
this._username = userName;
this._password = password;
this._surname = surname;
this._lastname = lastName;
this._birthdate = birthdate;
this._avatar = form.avatar;
this._messages = new Array();
this._messagesCount=0;
}
Run Code Online (Sandbox Code Playgroud)
Ily*_*din 45
你不能这样做,因为JavaScript不是强类型语言,它不会看到form和userName之间的区别.您可以创建多个函数createUserFromForm(form),createUserFromUserInfo(userName, password,...)或者您可以尝试使用不指定参数的单个构造函数,然后使用参数集合来检查输入并决定要执行的操作.
小智 21
我喜欢Ilya Volodins的回答,我想我会以此为例:
function foo() {
var evt = window.event || arguments[1] || arguments.callee.caller.arguments[0];
var target = evt.target || evt.srcElement;
var options = {};
if (arguments[0]) options = arguments[0];
var default_args = {
'myNumber' : 42,
'myString' : 'Hello',
'myBoolean' : true
}
for (var index in default_args) {
if (typeof options[index] == "undefined") options[index] = default_args[index];
}
//Do your thing
}
//then you call it like this
foo();
//or
foo({'myString' : 'World'});
//or
foo({'myNumber' : 666, 'myString' : 'World', 'myBoolean' : false});
Run Code Online (Sandbox Code Playgroud)
可能有更好的方法,但这只是一个例子.
不,你不能,JavaScript不支持任何类型的重载.
你可以做的是将已经填充了值的对象传递给构造函数,然后从对象中获取值,但这会复制代码.
或者您可以创建一个默认构造函数并添加诸如initFromUser或setFromForm之后的方法,然后获取相应的参数并设置对象值,new User().initFormForm(form)看起来非常干净.
您可以使用 ES6 特性创建构造函数,如下所示。
class Person {
constructor(name, surname) {
if (typeof name === "object") {
this.name = name.name;
this.surname = name.surname;
} else {
this.name = name;
this.surname = surname;
}
}
}
const person1 = new Person("Rufat", "Gulabli");
const person2 = new Person({ name: "Rufat", surname: "Gulabli" });
const person3 = new Person();
console.log(person1);
console.log(person2);
console.log(person3);
Run Code Online (Sandbox Code Playgroud)
打印:
小智 5
通过计算参数的数量来重载构造函数或任何其他Javascript函数:
function FooString()
{ if(arguments.length>0)
{ this.str=arguments[0];
return;
}
this.str="";
}
var s1=new FooString;
var s2=new FooString("hello world");
Run Code Online (Sandbox Code Playgroud)
您还可以通过检测缺少多少参数来设置默认参数.
| 归档时间: |
|
| 查看次数: |
33679 次 |
| 最近记录: |