The beginnings of a complicated relationship
var myObject = {
myProperty: "Some Data Value",
myMethod: function(){
console.log('I do things');
}
};
var emptyObject = {};
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
//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: