Here are some notes that I have discovered and would like to share with fellow beginners of OO JavaScript
Reference:http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
Key Learnings : -
a. JavaScript’s support for OO is very different from that given by C++, Java
b. a JavaScript function is really an object with executable code associated with it. and hence every function in JavaScript gets a “this” operator which refers to itself
Example-
function displayQuote() {
// the value of "this" will change; depends on
// which object it is called through
alert(this.memorableQuote);
}
var williamShakespeare = {
"memorableQuote": "It is a wise father that knows his own child.",
"sayIt" : displayQuote
};
var markTwain = {
"memorableQuote": "Golf is a good walk spoiled.",
"sayIt" : displayQuote
};
var oscarWilde = {
"memorableQuote": "True friends stab you in the front."
// we can call the function displayQuote
// as a method of oscarWilde without assigning it
// as oscarWilde’s method.
//"sayIt" : displayQuote
};
williamShakespeare.sayIt(); // true, true
markTwain.sayIt(); // he didn’t know where to play golf
// watch this, each function has a method call()
// that allows the function to be called as a
// method of the object passed to call() as an
// argument.
// this line below is equivalent to assigning
// displayQuote to sayIt, and calling oscarWilde.sayIt().
displayQuote.call(oscarWilde); // ouch!
c. You declare and setup classes by setting up functions in their name
d. Every object in JavaScript is created as a copy of an existing example object, and every class definition, so to speak , has the keyword “prototype” associated with it giving us developers access to the prototype of the class that we are setting up. ”Any properties and methods of this prototype object will appear as properties and methods of the objects created from that prototype’s constructor. You can say that these objects inherit their properties and methods from their prototype. “
e. Every “prototype” has a “constructor” property to it. and since the class declaration/definition itself is a function, this “constructor” property simply refers back to this function. (some recursion this is).
f. “Every JavaScript object inherits a chain of prototypes, all of which terminate with Object.prototype, which is the ultimate base prototype for all prototypes. “
g.JavaScript supports closures. “Closure” when crudely translated to simpler english means anonymous functions. And a more specific meaning would be “A closure is a runtime phenomenon that comes about when an inner function (or an inner anonymous method) is bound to the local variables of its outer function.”
Inheritance works this way – http://javascript.crockford.com/prototypal.html