Every function can be used to construct an object.
function X() { this.value = 12; } var y = X() var z = new X();
y
and z
?this.value
do?this
for both function executions?z.__proto__
?Objects all have a prototype that:
__proto__
property,inheritby a chaining prototypes.
Methods and properties are defined using the
prototype
property of a function.
function Dozen() { this.value = 12; } Dozen.prototype.numberOfItems = function(x) { return x*this.value; } Dozen.prototype.numberOfUnits = function(x) { return x/this.value; }
A object property can be controlled by functions:
var Audio = { _volume: 7, get volume() { return this._volume; }, set volume(level) { if (level<0 || level >10) { throw "Invalid value"; } this._volume = level; } }
Now, Audio.volume = 11
throws an error.
What about Audio._volume
?
The value is hidden with a closure:
function Audio() { var audioLevel = 7; Object.defineProperty( this,"volume", { get: function() { return audioLevel; }, set: function(level) { if (level<0 || level >10) { throw "Invalid value"; } audioLevel = level; } } ); }
There are too manytricksin JavaScript to name to make up for the fact it isn't designed all that well.
Inheritance
function Dragon() { this.__proto__.__proto__.constructor(); // Yes, inherited constructors do not execute by default } Dragon.prototype.breathFire = function() { console.log("Hot, hot, hot!"); } Dragon.prototype.__proto__ = WingedCreature.prototype; function WingedCreature() { this.numberOfWings = 2; } WingedCreature.prototype.fly = function() { console.log("I can fly. Whoohoo!"); }