I have an object written like this:
Object1.prototype = { isInit: false, Get : function (){} }
Now I'd like to add a constructor which takes one parameter. How can I do it?
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.
Following is the syntax to create a function using Function( ) constructor along with the new operator. The Function() constructor expects any number of string arguments. The last argument is the body of the function – it can contain arbitrary JavaScript statements, separated from each other by semicolons.
TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class's field are the same.
Class declaration
var User = function(name, age) { // constructor } User.prototype = {}
Instance variables (members)
var User = function(name, age) { this.name = name; this.age = age; } User.prototype = {}
Static variables
var User = function(name, age) { this.name = name; this.age = age; } User.prototype = { staticVar: 15, anotherStaticVar: 'text' }
Here I defined two static variables. Each User instance has access to these two variables. Note, that we can initialize it with value;
Instance functions (methods)
var User = function(name, age) { this.name = name; this.age = age; } User.prototype = { getName: function() { return this.name; }, setName: function(name) { this.name = name; } }
Usage example:
var user = new User('Mike', 29); user.setName('John'); alert(user.getName()); //should be 'John'
Static functions
var User = function(name, age) { this.name = name; this.age = age; } User.create = function(name, age) { return new User(name, age); } User.prototype = {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With