Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in JavaScript objects

Tags:

javascript

oop

Can JavaScript classes/objects have constructors? How are they created?

like image 344
Ali Avatar asked Jul 11 '09 16:07

Ali


People also ask

What is constructor and object?

Object Types (Blueprints) (Classes) They only create single objects. Sometimes we need a "blueprint" for creating many objects of the same "type". The way to create an "object type", is to use an object constructor function. In the example above, function Person() is an object constructor function.

What is a constructor in JavaScript explain with an example?

In JavaScript, a constructor function is used to create objects. For example, // constructor function function Person () { this.name = 'John', this.age = 23 } // create an object const person = new Person(); Run Code. In the above example, function Person() is an object constructor function.

What is constructor method JavaScript?

The constructor() method is a special method for creating and initializing objects created within a class.

What is the difference between constructor and object in JavaScript?

A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object.


1 Answers

Using prototypes:

function Box(color) // Constructor {     this.color = color; }  Box.prototype.getColor = function() {     return this.color; }; 

Hiding "color" (somewhat resembles a private member variable):

function Box(col) {    var color = col;     this.getColor = function()    {        return color;    }; } 

Usage:

var blueBox = new Box("blue"); alert(blueBox.getColor()); // will alert blue  var greenBox = new Box("green"); alert(greenBox.getColor()); // will alert green 
like image 74
Nick Avatar answered Oct 13 '22 09:10

Nick