Javascript Oop Classical
JavaScript is a prototypal inheritance language. That means that objects
can inherit properties directly from other objects. The language is
class-free. This is a radical departure from other languages. Most languages
today are classical. Prototypal inheritance is powerfully expressive, but is
not widely understood. JavaScript itself is not confident in its prototypal
nature, so it offers an object-making syntax that resemble classical languages.
Few classical programmers found prototypal inheritance to be acceptable, and
classically-inspired syntax obscure the language's true prototypal nature. It
is the worst of both worlds.
If a function is invoked with the 'new' keyword, then the new object will be
created with a hidden link to the value of the function's prototype member, and
this will be bound to that new object. The 'new' prefix also changes the
behavior of the return statement.
// Create a constructor function called Quo.
// It makes an object with a status property.
var Quo = function (str) {
this.status = str;
};
// Give all instances of Quo a public method:
Quo.prototype.get_status = function () {
return this.status;
};
// Make an instance of Quo:
var myQuo = new Quo("confused");
Functions that are intended to be used with the new keyword / prefix are called
constructors. By convention, they are kept in variables with a capitalized
name. If a constructor is called without the new prefix, very bad things can
happen without a compile-time or runtime warning (probably, the linkage, as
mentioned above, is not established), so the capitalization convention is really
important.
If the function was invoked with the new prefix, and the return value is not an
object, then this (the new object) is returned instead.
page revision: 1, last edited: 02 Dec 2016 06:08