I am coming at Javascript from a classical OOP background and am having trouble with understanding the prototype.
Given the code example below:
- How would I call/execute bar in foo?
- why use the “privileged” function instead of putting it on the prototype?
-
This is probably answered in Q1 but can bar1 and bar2 call each other?
function foo() { this.property = "I'm a property"; this.privileged = function() { // do stuff } } foo.prototype.bar = function() { // do stuff } foo.prototype.bar2 = function() { // stuff }
There’s a lot of FUD about this to this day.
1). Simple usage:
2). This basically creates a closure that can only be modified on the instance. Not a private at all (since anything can talk to it through the object instance), but rather an individual copy of a function, where each instance of the object gets a new copy of the function. You can alter the function itself, but you cannot alter it globally. I’m not a big fan of this method of creating things.
3). Yes:
For edification, I built you a fiddle which should help show how things get called:
http://jsfiddle.net/7Y5QK/