“This” Property and Understanding It

Timthumb (9)

When a function is created, a keyword called “this” is created which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method. The this property is used in ‘this.gender’ simply refers to the object on which the function is operating.

The topic of this can be confusing, but it does not have to be. Just remember that, in general, this property is used inside of functions to refer to the object of the function is contained within, as replicate to the function itself. The keyword this looks and acts like any other variable, except you can’t modify it. As opposed to arguments and any parameters sent to the function, this is a keyword in the called object.

The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize. The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.

var foo = 'foo';
var myObject = {foo: 'I am myObject.foo'};
var sayFoo = function() {
myObject.sayFoo = sayFoo;
myObject.sayFoo(); // logs 'I am myObject.foo' 12
sayFoo(); // logs 'foo'

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.

Leave a Reply

Your email address will not be published. Required fields are marked *