Constructor Stealing

Description

Constructor Stealing is to call the Shape constructor from within the Rectangle constructor.

The apply() and call() methods can be used to execute a constructor on the newly created object.

Example


function Shape(){//from   w w w . j a v a  2 s  . c o m
    this.colors = ["red", "blue", "green"];
}

function Rectangle(){
    //inherit from Shape
    Shape.call(this);
}

var instance1 = new Rectangle();
instance1.colors.push("black");
console.log(instance1.colors);    //"red,blue,green,black"

var instance2 = new Rectangle();
console.log(instance2.colors);    //"red,blue,green"

The code above generates the following result.

Passing Arguments

One advantage that constructor stealing offers over prototype chaining is the ability to pass arguments into the Shape constructor from within the Rectangle constructor.


function Shape(name){//  w ww.ja va2s . c o m
    this.name = name;
}
function Rectangle(){
   //inherit from Shape passing in an argument
   Shape.call(this, "Nicholas");

   //instance isDrawable
   this.age = 29;
}
var instance = new Rectangle();
console.log(instance.name);    //"Nicholas";
console.log(instance.age);     //29

The code above generates the following result.

Problems with Constructor Stealing

Methods must be defined inside the constructor, so there's no function reuse.

Methods defined on the Shape's prototype are not accessible on the Rectangle.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions