Brian,
In your case `this` is bound to the global object because you forgot to use
`new` operator. The `new` operator creates a new object, then calls the
operand and binds the new object to a special member `this`. But when you
don't use `new` this magic does not happen and `this` is bound to the global
object.
You can try it out in the console:
> (function () { console.log(this); }()); // DOMWindow
> (new function () { console.log(this); }()); // Object
Anton
On 25 February 2011 10:27, Brian Earwood <[email protected]> wrote:
> Hi everyone,
>
> I've been fiddling around with different ways of creating objects and I'm
> having some growing pains in leaning the situations where one way would be
> better than another.
>
>
> I'm seeing that when I use the immediately invoked way:
>
> var Class = (function(){
>
> this.activate = function() {
> console.log('activate called');
> };
>
> this.deactivate = function() {
> console.log('deactivate called');
> };
>
> return function(){
> this.brian= function() {console.log("Brian wuz here.");};
> this.kayla= function() {console.log("Kayla wuz here.");};
> }
> })();
>
> I can access "activate" and "deactivate" from the console directly. Does
> this mean that those functions are global now? Is that a problem?
> I can access "brian" and "kayla" by saying:
>
> myClass = new Class()
> myClass.brian();
> myClass.kayla();
>
> So that constructor way of instantiating seems like a more
> traditional/classical way of writing it.
>
> Writing non immediately invoked functions creates a different situation...
>
> I guess I'm just wondering if there's a recent book or something that goes
> over all of these differences in detail, and when they should be used?
>
>
> Thanks for the help and a great group!
>
> Brian
>
> --
> 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]
>
--
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]