Programming with prototypes cheatsheet

BrenDt
Just JavaScript
Published in
1 min readAug 14, 2015

--

Creating objects

var Foo = {
init(id) {
this.type = 'foo';
this.setId(id);
},

setId(id) { this.id = id; },
getId() { return this.id; },
};
var baz = Object.create(Foo);
baz.init(10);

Inheritance

var Foo = {
setId(id) { this.id = id; },
getId() { return this.id; },
};
var Bar = Object.create(Foo);
Bar.setName = function(name) {
this.name = name;
};
Bar.getName = function() {
return this.name;
}
var baz = Object.create(Bar);

Polymorphism

var Foo = {
init(id) {
this.type = 'foo';
this.setId(id);
},
};
var Bar = Object.create(Foo);
Bar.init = function(id, name) {
this.type = 'bar';
this.id = id;
this.name = name;
}
var baz = Object.create(Bar);
baz.init(10, 'test');

Immutability

var Foo = { };
Object.defineProperty(Foo, ‘type’, {
value : ‘FOO’,
writeable : false,
configurable : false,
enumerable : true,
});

Static functions

var Foo = {
addition : 5,
add(param) {
return param + this.addition;
},
};
var baz = Object.create(Foo);
var result = Foo.add(3);

More information about all these patterns can be found here.

--

--