Wanted to share my own explanation of the prototype, __proto__, and constructor properties. This has suddenly become very clear to me recently, so I hope this helps someone.
To elaborate on __proto__ and prototype, they are similar, but not exactly the same. The difference is that
__proto__ is a property of an
object (usually a class instance), while
prototype is a property of a
constructor function. An object's __proto__ is a reference to its constructor's prototype.
Example:
Code:
// constructor for the Game class
function Game () {
// code
}
// create a method for the Game class
Game.prototype.printMe = function () {
trace "Game";
}
// create an object that's an instance of the Game class
chess = new Game();
chess.printMe() // output: "Game"
- now you have a class instance (chess) and a class constructor (Game)
- the name of the constructor function determines the name of the class
- the Game function is automatically given a prototype property
- we can use Game's prototype property to attach methods (like printMe)
So far so good? Onward...
- chess is created with the Game constructor, so it belongs to the Game class
- chess is automatically given a __proto__ property that points to the prototype property of Game
- this means that chess.__proto__ == Game.prototype
Some other info that's interesting:
1)
- Game.prototype has a __proto__ property as well
- Game.prototype.__proto__ == Object.prototype
- thus, chess.__proto__.__proto__ == Object.prototype
2)
- you can reference the Game constructor function with chess.__proto__.constructor
- suppose you wanted to make an object similar to chess, but you didn't know what class it belonged to
- you could make the object by accessing chess' constructor:
checkers = new chess.__proto__.constructor();
3)
- Game.prototype.constructor is the same as Game
- some people use something like "Game.prototype.constructor" in class inheritance
- it works, but it's redundant
[there's also a good explanation on p.269 of "Actionscript: The Definitive Guide" by Colin Moock]