Constructors in JavaScript objects
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
Adding Properties to existing Javascript Objects from Object Constructors
You can add additional properties after the fact:
function funcConstruct(first,last,age) {
this.firstName = first,
this.lastName = last,
this.age = age,
this.fullNameAge = function() {
return this.lastName + ', ' + this.firstName + ', ' + this.age
}
};
var johnDoe = new funcConstruct('John', 'Doe', 52);
johnDoe.foo = "bar";
You are using the function constructor pattern, but note that there are other javascript object encapsulation patterns you can use depending on your use case some are better than others. In my opinion, I would use the function constructor pattern only if I was using pre ES6, if using >=ES6 (ES2015) I would use a class, and only if I needed a bunch of instances of the object. Otherwise, I would rather use the revealing module pattern if only a single instance of the object is required. Use fun
No use re-inventing the wheel, the accepted answer and some other highly voted answers to this question give a good summary. This video explains some of the confusion around using this
in javascript and provides an opinion that it is probably best to avoid this
where possible.
when to use class/object constructor
class
syntax is mostly (but not entirely) syntactic sugar for creating constructor functions and filling in the object on their prototype
property. You can do almost everything class
does writing constructor functions explicitly and adding properties to their prototype
property and using some methods on the ES2015+ Reflect
object, but it's doing so is much more verbose and error-prone. (The number of things that you can only do with class
syntax is going to increase before too long as the private fields and methods proposals mature.) I've given an overview of how class
syntax can be emulated with earlier constructs in my answer to What benefits does ES2015 (ES6) class
syntax provide? here.
As to when to use which, it's mostly a matter of style for you and your team to decide. Even for the things that you can't literally do without class syntax (such as private fields, which will likely advance to the living specification at some point this year and be in ES2021), you can do similar things in other ways.
But:
- If what you're doing requires
class
syntax (for instance, if you want to use private fields, once they're added [or now via transpilation]) and you want to do that thing specifically rather than something else that's similar to it, then you'll need to useclass
syntax. - If not, it's largely a matter of style for you and your team to decide.
Object constructor from template object
It is possible and straight forward after all to have properties in a constructor in class syntax based on arguments passed to the constructor. Mapping a function along the lines of a => this[a]
onto an array of the property keys does it. In the snippet is an example where there is also an assignment to the property.
// example objectsconst someObject = { a: 0, b: 0, c: 0,};
const otherObject = { a: 1, c: 137, d: 42,};
class Test { constructor(template, data) { Object.keys(template).map(a => { this[a] = data[a] ? data[a] : template[a]; return null; }); Object.seal(this); }}
const test = new Test(someObject, otherObject);console.log(test);
Constructor concept in JavaScript
First of all the person
is a regular JavaScript function. When you call it, of course, lines:
this.firstName = "";
this.lastName = "";
are executed. Constructor function is rather a concept than a something really existing in the JS language. You need constructors to create new similar objects by calling new MyCtr()
. At the same time you need regular functions to encapsulate piece of logic and make it reusable in different places without copy/paste the code.
You can use all functions in JavaScript as a constructor. Just add new
keyword in front of function call expression. This thing changes the context of execution of the function. Without new
the function is executed against global object (window
in a browser). And this
variable inside the function refers to the context.
Not every function is ready to be a constructor. Usually, constructor functions are doing something with this
variable which is a reference to an object which is created during new MyCtr()
call. Also, constructor functions never return a value.
Lets look at few examples (you can execute it directly in the browser's console):
function foo() {
this.a = 1;
}
foo(); // using function as a regular function. Ctx is window.
console.log(window.a); // prints "1"
foo.call(window); // explicitly specify execution ctx. The same as just foo() call
var instance = new foo(); // using foo as a constructor
console.log(instance.a); // prints "1"
// actually you can do it without new keyword
var instance = {}; // manually create new object
foo.call(instance); // manually call foo against this object
console.log(instance.a); // prints "1"
// However, the code above is not strictly equivalent to the code using new.
// It omits the concept of prototype, but it's enough for our current task.
Regarding functions and files. There is no such thing in the language like in the Java that each class must be placed in the separate file. You can put all your functions within one file and then use it as constructors or not. However, the best practice is to reside one constructor function (read as class) per one file (called module).
Object.constructor===Object.constructor.constructor // why?
Because Object
is a Function
, and the Function
constructor is a Function
, so its constructor is itself.
An "object" is the fundamental building block of object-oriented programming. Object
, in JavaScript, is a constructor function (like Date
, or RegExp
). Its job is to initialize new instances of objects created by the interpreter via the new
keyword.
This may be off-topic, or not, since you're asking about constructors:
Any function in JavaScript can be a constructor function; it's purely a matter of how you use it. Consider:
function Foo() {
}
If I call that like this:
var f = Foo();
...it's just a boring old function, and f
receives undefined
(since Foo
doesn't return anything). But if I call it like this:
var f = new Foo();
...I'm using it as a constructor function and something more interesting happens:
- The interpreter creates a new, blank object.
- The interpreter sets the new object's underlying prototype to be
Foo.prototype
. - The interpreter calls
Foo
in a way that makesthis
refer to the new object. - When
Foo
completes, ifFoo
doesn't return a value (or doesn't return an object), the result of thenew
expression is the object created in step 1. (IfFoo
returns an object, that object is used instead; that's an advanced thing most people don't have to do.)
Creating a array of objects using a constructor
Try this, JsBin sourses
var people = [];
function Person(name, age){ // Function constructor
this.name = name; // do not forget 'this.'
this.age = age;
}
function addPerson(name,age){
var p = new Person(name,age); // here we create instance
people.push(p);
}
addPerson("Petia", 80);
addPerson("Vasia", 20);
function totalAge(){
var total = 0; // do not name local variables same as function
var i; // use var for i variable, otherwise it would be global variable
for (i = 0; i < people.length; i++){
total += people[i].age;
}
return total;
}
var total = totalAge();
console.log(total);
Related Topics
Sort Array by Firstname (Alphabetically) in JavaScript
How to Escape Regular Expression Special Characters Using JavaScript
How to Get the Text Node of an Element
How to Submit a Form Using JavaScript
Display Posts in Descending Posted Order
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
How to Compute the Sum and Average of Elements in an Array
Window.Onbeforeunload and Window.Onunload Is Not Working in Firefox, Safari, Opera
How to Fix Error: Listen Eaddrinuse While Using Nodejs
How to Listen to a "Style Change" Event
How to Edit a JavaScript Alert Box Title
JavaScript Setinterval and 'This' Solution
What Do Square Brackets Around a Property Name in an Object Literal Mean
Preserving a Reference to "This" in JavaScript Prototype Functions