|
JavaScript Objects
Classless creation
Create data object using constructor
|
function Person(id,age) { this.id=id; this.age=age; }
|
o=new Person("bob",60);
|
id=bob age=60
|
Create data object directly
|
n/a
|
o = new Object(); o.id="bob"; o.age=60;
|
id=bob age=60
|
Create data object directly [alternative]
|
n/a
|
o={id:"bob",age:60};
|
id=bob age=60
|
Create behavioural object using constructor
|
function Person(id,age) { this.id=id; this.age=age; this.makeOlder=makeOlder function makeOlder() { // always need "this" prefix this.age++; } }
|
o=new Person("bob",60); o.makeOlder();
|
id=bob age=61
|
Classless inheritance
Classless single inheritance
|
function Rect(h,w) // superclass { this.h=h; // height this.w=w; // width this.x=0; // x pos this.y=0; // y pos this.move = function move(x,y) { this.x+=x; this.y+=y; } } function Square(w,a) // subclass { Rect.call(this,w,w); this.angle=a; } Square.prototype = Object.create(Rect.prototype); Square.prototype.constructor = Square; o = new Square(10,45); o.move(1,1);
|
t = ( o instanceof Square && o instanceof Rect && o.x==1 && o.y==1 && o.h==10 && o.w==10 && o.angle==45 )
|
true
|
Version: JavaScript-C24.8.1
Description: Debian GNU/Linux 8.2 (jessie)
Release: 8.2
Codename: jessie
|