On Mon, Apr 11, 2011 at 5:53 AM, <[email protected]> wrote:
> Hello,
>
> I start to learn JS.
>
>
Welcome, Sam!
> **************************
> var f1 = function () {
> this.v1 = 5;
> }
>
Here you define a simple function. The only weird thing is the "this"
references inside. Now, "this.v1" doesn't mean, "give 'f1' the 'v1'
property". It means, "when 'f1' is called bound to an object, give that
object the property 'v1' and set it's value to '5'". By default (in a
browser at least... there are other ways to use Javascript, but that's a
later lesson), 'this' will be the 'global' browser object. So, "f1" does
not have a "v1" property. However, when you write
> var f2 = new f1();
>
you are actually saying, "create a new, empty object; assign it to 'this';
call 'f1', and assign that same object (or whatever 'f1' returns) to 'f2'.
So, "f2" *does* have a "v1" property.
> f1.prototype.get_v1 = function () { return this.v1; };
>
f1.get_v1() // nothing
>
Here, you are invoking "get_v1" on the "f1" object. You have correctly set
the function on the prototype object of "f1"... excellent. However, when
calling "get_v1", "this" is pointing to the browser's global object, and the
global object doesn't have a "v1" property. Hence, "undefined" is returned.
Does that help at all?
_jason
>
--
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]