Afshin Mehrabani
Afshin Mehrabani

Reputation: 34979

Why using this declare a global variable in functions?

I have this code:

function boo() {
    this.is_global = "Yes!";
}

When I run the boo();, I have is_global in window object, I mean the is_global goes into global context.
I expected to have is_global in boo function only.

Is this a normal behavior?

Upvotes: 1

Views: 180

Answers (4)

user1726343
user1726343

Reputation:

this refers to the window. If you want to refer to the function, use:

arguments.callee.is_global = "Yes!";

Now:

window.is_global; //undefined
boo.is_global; //"Yes!"

An alternative way would be to simply refer to boo by its own name when adding properties to it.

function boo() {
    boo.is_global = "Yes!";
}

Note that this modifies the original boo function object. If you wish to modify all instances of boo resulting from using it as a constructor instead, please see the other answers here.

Upvotes: 2

Bergi
Bergi

Reputation: 665256

Check out MDN's introduction to the this keyword.

I guess you wanted to declare a local variable, so use a var statement.

Upvotes: 1

Quentin
Quentin

Reputation: 944202

To have this be "the function being called", you have to call the function as an object constructor (using new).

var foo = new boo();

This will create an instance of boo with the property is_global. This will not create a property on the constructor function itself. See a demo.

If you don't use new (or a method such as apply), then this is "The object on which the function is called". Since there is no object in this case, the default object is used. In the context of a web browser, the default object is window. So:

var foo = boo();

is the same as

var foo = window.boo();

and this is window inside boo.

Upvotes: 1

Michael Mior
Michael Mior

Reputation: 28752

Yes, this is normal behaviour. If your function is defined globally, this is just window and anything added to window is global.

Upvotes: 5

Related Questions