My question is:
function Foo()
{
this.foo = "bar"; // <- What is "this" here?
}
From what I can tell it depends on how Foo
is used, i.e. as a constructor or as a function. What can this
be in different circumstances?
My question is:
function Foo()
{
this.foo = "bar"; // <- What is "this" here?
}
From what I can tell it depends on how Foo
is used, i.e. as a constructor or as a function. What can this
be in different circumstances?
Its depends on how that function is used, there are two basic types in which we can use functions
will see one by one
1.Function
Here 'this' keyword points to window object.
By default, this should always be the window Object, which refers to the root - the global scope. So when we console.log(this); from our function, as it’s invoked by the window (simply just called), we should expect the this value to be our window Object:
2.Function as an Object
Here 'this' keyword points to newly created example object.
In JavaScript everything is object even functions. When you say
this.foo
in following codefoo
becomes member variable ofFoo
objectThe
this
keyword refers to the object the function belongs to, or thewindow
object if the function belongs to no object.It's used in OOP code, to refer to the class/object the function belongs to For example:
This alerts:
Hello, world
You can manipulate which object
this
refers to by using theapply()
orcall()
functions. (A very very handy feature at times)Read what Douglas Crockford has to say on the matter, to quote him from A Survey of the JavaScript Programming Language:
Also 'this' can change depending on how your function is invoked, read on apply function and call function.
I would recommend that you spend time learning form one of JavaScript's greatest minds in his (free) presentations, linked from here.
In JavaScript, the convention (and this is only a convention) is that any function that begins with a capital letter is to be used as a constructor. Then, one would call
var foo = new Foo()
andthis
would refer to the newly created object that is about to be referenced byfoo
.Of course, there is nothing stopping you from calling
Foo()
on its own, in which casethis
would then refer to the object from which the function was called. To avoid confusion, that is not recommended.