how to declare parameterized constructors in JavaScript?? How it can be achieved in JavaScript??
public class A()
{
//variable declaration
public A()
{
//do something
}
public A(int a)
{
//do something
}
public A(int a,int b)
{
//do something
}
}
3 Answers 3
JavaScript does not support overloading based on argument definitions.
Write a single function and check which arguments were received.
function A(a, b) {
if (typeof a === "undefined") {
// ...
} else if (typeof b === "undefined") {
// ...
} else {
// ...
}
}
Comments
Any function in javascript can be a constructor
function A(paramA, paramB) {
this.paramA = paramA;
this.paramB = paramB;
//do something
}
A.prototype.method1 = function(){
console.log(this)
console.log('Inside method 1' + this.paramA)
}
var a = new A(1, {name: 'Name'});
console.log(a.paramA);
console.log(a.paramB.name)
a.method1()
All instance variables can be created using this.<variable-name>=<value>;.
Instance methods can be created using the prototype property of the constructor function.
You can read more about constructors
Simple "Class" Instantiation
Simple JavaScript Inheritance
You also can check whether a parameter exists using
if(paramB == undefined) {
//do something if paramB is not defined
}
1 Comment
var Class = function(methods) {
var klass = function() {
this.initialize.apply(this, arguments);
};
for (var property in methods) {
klass.prototype[property] = methods[property];
}
if (!klass.prototype.initialize) klass.prototype.initialize = function(){};
return klass;
};
var Person = Class({
initialize: function(name, age) {
this.name = name;
this.age = age;
},
initialize: function(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
});
var alice = new Person('Alice', 26);
var rizwan = new Person('riz', 26, 'm');
alert(alice.name + ' - alice'); //displays "Alice"
alert(rizwan.age + ' - rizwan'); //displays "26"
http://jsfiddle.net/5NPpR/ http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=OJ1MheBA5Xa
typeof a == 'undefined')