User Tools

Site Tools


javascript_constructors

Javascript Constructors

This is a constructor

It is considered good practice to name constructor functions with an upper-case first letter.

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

*Note: “this” is not a variable. It is a keyword. You cannot change the value of “this”.

This will add the property “nationality”, and the function name() to myFather, but not myMother.

myFather.nationality = "English";
myFather.name = function () {
    return this.firstName + " " + this.lastName;
};

To add a property or function to both myFather and myMother, add it to the constructor

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    //this is a default value
    this.nationality = "English";
    this.name = function() {return this.firstName + " " + this.lastName;};
}

Built in constructors in Javascript

var x1 = new Object();    // A new Object object
var x2 = new String();    // A new String object
var x3 = new Number();    // A new Number object
var x4 = new Boolean();   // A new Boolean object
var x5 = new Array();     // A new Array object
var x6 = new RegExp();    // A new RegExp object
var x7 = new Function();  // A new Function object
var x8 = new Date();      // A new Date object

But there is no reason to create complex objects. Primitive values are much faster.

var x1 = {};            // new object
var x2 = "";            // new primitive string
var x3 = 0;             // new primitive number
var x4 = false;         // new primitive boolean
var x5 = [];            // new array object
var x6 = /()/           // new regexp object
var x7 = function(){};  // new function object
javascript_constructors.txt · Last modified: 2018/09/07 14:29 by admin