It's like 'this' and like that and like this and....wat??
The beginnings of a complicated relationship
Let's remember a few things about Objects:
-
Objects can have properties (values)
-
Objects can have methods (functions)
-
Objects can be empty
var myObject = {
myProperty: "Some Data Value",
myMethod: function(){
console.log('I do things');
}
};
var emptyObject = {};
Remember these things about Functions:
- Whenever ANY function is invoked JavaScript with or without explicit parameters that you the programmer writes, 2 implicit parameters are also passed:
- arguments
- this
-
this refers to the object which the current function is associated or belongs to. Otherwise known as the function context.
- All functions are objects (first class objects)
- All objects can have properties and that functions can be properties of objects
- this ALWAYS refers to an instance of an Object
- A function ALWAYS belongs to an Object
Invoking Functions
Functions can be invoked/called in 4 ways:
As a function:
function hackThePlanet(){
//do things to hack the planet
//this refers to the global context or window object
}
hackThePlanet();
As a method:
var hacker = {
hackThePlanet: function(){
//hack the things
//this refers to the hacker object
}
};
hacker.hackThePlanet();
As a constructor:
With call/apply:
TBD
TBD
The main difference between all methods is what determines the function's context or this
The easiest way to remember the previous 2 rules is that this refers to the object which the function belongs to.
If a function isn't the property of an object, it belongs to the window object or global scope.
this does not have a value until an object invokes the function where this is defined.
this is the global scope if you're just calling a function. If you're calling a property/method of an object(function is an object) this is the owning object context
Cool. Make Sense?
//What is this in the following scenarios?
function hackThePlanet(){
console.log(this);
}
hackThePlanet(); // Invoking as a function = ???
var destroy = hackThePlanet;
destroy(); // Invoking as a ??? = ???
var hacker = {
hackThePlanet : hackThePlanet, //assign a reference to our function defined above
loveThePeople : function(){
console.log(this);
}
};
hacker.hackThePlanet(); //Invoking as a ??? = ???
hacker.loveThePeople(); //???
hacker.allTheThings = function(){
console.log(this);
};
hacker.allTheThings(); //???
Let's try it out:
If you can understand this...
...you can understand all of that.
WAT!
Like this and like that and like this and...wat?
By Jason Sewell
Like this and like that and like this and...wat?
An exploration of the concept of this in JavaScript for only function invocation and method invocation. Constructor invokation and call/apply to come later.
- 2,397