Friday, 26 December 2014

Object

An Instance of a class.

In the example below we define a new class called Person.
var Person = function () {};

The object (class instance)

To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later. An alternative way to create an new instance is to use Object.create. This will create an uninitialized instance.

In the example above we define a class named Person. In the example below we create two instances (person1 and person2).
var person1 = new Person();
var person2 = new Person();


The Object.create() method creates a new object with the specified prototype object and properties.

Syntax

Object.create(proto[, propertiesObject])

Parameters

proto
The object which should be the prototype of the newly-created object.
propertiesObject
Optional.

Throws

Throws a TypeError exception if the proto parameter isn't null or an object.

Examples

Example: Classical inheritance with Object.create

Below is an example of how to use Object.create to achieve classical inheritance. This is for single inheritance, which is all that Javascript supports.
// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log("Is rect an instance of Rectangle? " + (rect instanceof Rectangle)); // true
console.log("Is rect an instance of Shape? " + (rect instanceof Shape)); // true

rect.move(1, 1); // Outputs, 'Shape moved.'
 
 
 
If you wish to inherit from multiple objects, then mixins are a possibility.
function MyClass() {
  SuperClass.call(this);
  OtherSuperClass.call(this);
}

MyClass.prototype = Object.create(SuperClass.prototype); // inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin

MyClass.prototype.myMethod = function() {
  // do a thing
};
The mixin function would copy the functions from the superclass prototype to the subclass prototype, the mixin function needs to be supplied by the user. An example of a mixin like function would be jQuery.extend.

No comments:

Post a Comment