Edit: for those people seeing this post in the future, this site was undoubtedly critical for me to digest Javascript. If you're coming from a traditional OOP background, I HIGHLY recommend it. The UML-esq diagrams were amazing.
I still can't get my head around what the .prototype property in Javascript is. Is it simply a reference to another object? Or is it a reference to a pointer to another object? I come from C/C++/x86 and just can't see how it works. Let's look at some examples of how I currently see things; it'd help to point out my errors to see how things work. I don't even know if some of these are valid syntax. Object
and Function
are the global object/function objects respectively.
1 // Global.prototype = ??
2 // Function.prototype = ??
3
4 var obj1 = {}; // obj1.prototype = Object
5 obj2 = {}; // obj2.prototype = Object
6
7 var func1 = function() {}; // func1.prototype = Function
8 func2 = function() {}; // func2.prototype = Function
9 function func3() {} // func3.prototype = Function
10
I'm so confused.
11 var Foo = function() { this.prop1 = 0; }
12 var foo = new Foo(); // should it be 'new Foo' or 'new Foo()'?
13 // Foo.prototype = Function
14 // foo.prototype = Foo
15 var Goo = function() { this.prop2 = 0; }
16 var goo = new Goo();
17 // goo.prototype = Goo
18 goo.prototype = new Foo();
19 // goo.prop1 now exists ?
I also don't understand swapping prototypes around.
20 function A () {
21 this.prop1 = 1;
22 }
23 function B () {
24 this.prop2 = 2;
25 }
26 function C () {
27 this.prop3 = 3;
28 }
29 C.prototype = new B();
30 var c = new C();
31 // c.prop1 = 1
32 // c.prop2 = 2
33 // c.prop3 = undefined
34 C.prototype = new A();
35 // c.prop2 = 2???
36 // c.prop3 = 3
I can't get a grasp on the concept. I don't quite understand. I don't get how cloned objects get their own local copies of data, but changes to the original object (the prototype) somehow cascade down to the clones. I've been fiddling around with FigureBug trying things out, but mentally I can't come up with an idea that is consistent with every example ive seen
C++ may be a huge monstrosity, but at least I know exactly what's going. Here... I'm using my best guess.. Just a new paradigm I suppose. Anyways, thanks if you can help out... I'm turned upside-down on this .prototype.