admin管理员组文章数量:1287569
is it possible to have more than one constructors for a class in javascript? i.e. one with zero parameters, one with one, one with two, etc...
if so, how?
thanks!
is it possible to have more than one constructors for a class in javascript? i.e. one with zero parameters, one with one, one with two, etc...
if so, how?
thanks!
Share Improve this question edited Feb 7, 2011 at 9:30 Haim Evgi 126k46 gold badges222 silver badges226 bronze badges asked Feb 7, 2011 at 9:29 clampclamp 34k75 gold badges207 silver badges305 bronze badges 2- What you want shall be called "polymorphic function-constructor". look on highdots./forums/javascript/… – Haim Evgi Commented Feb 7, 2011 at 9:32
- Possible duplicate of JavaScript pattern for multiple constructors – Suma Commented Feb 24, 2017 at 9:31
2 Answers
Reset to default 9No, Javascript does not support function overloading.
However, inside every function you have access to an arguments
object, which holds all the arguments supplied to the function, declared or not. You can simply look at it and decide what exactly you want to do in your constructor.
Bad, unrefined example:
function Foo() {
function singleParamConstructor(foo) {
...
}
function twoParamConstructor(foo, bar) {
...
}
switch (arguments.length) {
case 1 :
singleParamConstructor(arguments[0]);
break;
case 2 :
twoParamConstructor(arguments[0], arguments[1]);
break;
...
}
}
this might help: JavaScript constructor parameter types
本文标签: javascript different constructors for same type of objectStack Overflow
版权声明:本文标题:javascript: different constructors for same type of object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741241380a2364045.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论