Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to define a Constructor

Tags:

javascript

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?

like image 400
user256034 Avatar asked Feb 17 '11 15:02

user256034


People also ask

How do you define a constructor in JavaScript?

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.

How do you define a constructor?

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.

How do you assign a function to a variable with a JavaScript constructor?

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.

How do you define a constructor in TypeScript?

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.


1 Answers

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 = {} 
like image 66
Andrew Orsich Avatar answered Sep 23 '22 09:09

Andrew Orsich