************************** var f1 = function () { this.v1 = 5; } f1.prototype.get_v1 = function () { return this.v1; }; var f2 = new f1();f1.v1 // return nothing f1.get_v1() // nothing f2.v1 // return 5 f2.get_v1() // return 5 ************************** Why f1.v1 and f1.get_v1 return nothing ?
Your example deals with objects, functions and constructors. Constructors are functions used in a special way, and functions are objects. So constructors are objects as well. Objects can have properties. Functions for example have a property 'prototype', which is important when they are used as constructors.
f1.v1
You are trying to access the property 'v1' of f1. This has not been declared, so undefined is returned.
f1.get_v1()
You are trying to call the method 'get_v1' of f1. This has not been declared either, so a TypeError is thrown. You might say, hey, I defined that function in its prototype, so it should be taken from there. Unfortunately, 'prototype' and 'prototype' are not the same (though they are related).
When you create an object using the 'new' keyword (as you did in 'var f2 = new f1()'), the newly created object has an *internal* link to an object called prototype. When trying to access a property which is not found in the object itself, the javascript interpreter looks for it in the object's prototype. Now, what is this prototype object the internal link links to? It's the prototype property of the constructor function.
So your line 'f1.prototype.get_v1...' adds a property to the prototype of the constructor function f1. When you create a new object ('var f2 = new f1();') that object has an internal link to f1.prototype. So now you do:
f2.get_v1()
get_v1 is not defined in f2 itself, but in its internal prototype. So it's found there.
f2.v1
When you created f2, the constructor function f1 assigned it a property v1, which is publicly accessible.
The next interesting questions are: What is 'this' in f1? And what is 'this' in f1.prototype.get_v1 when called via 'f2.get_v1()'?
Hope that helped, Matt -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
