Managing Execution Context in JS
this
n. The circumstances in which an event occurs; a setting.
Context
Execution
v. To perform; do.
Execution Context
n. The object a function lives inside of.
The setting a function performs in.
arguments
this
var math = {
addTwo : function (num1, num2) {
console.log(arguments);
console.log(this);
x = x + num1 + num2;
return x;
},
x : 5
}
An array-like object that contains the parameters passed into the function in order.
The calling context of the function- the object the function exists inside of.
function defaultContext () {
console.log(this);
}
var cat = {
name: "Felix",
furColor: "black"
}
defaultContext.call(cat);
This function's calling context is the global object
We can set the context explicitly
function aGloballyScopedFunction () {
console.log("THIS IS: ", this)
}
aGloballyScopedFunction()
aGloballyScopedFunction.call(cat)
this
window || global
cat
this
var line = {
x1 : 0,
y1 : 0,
x2 : 2,
y2 : 2,
getSlope : function () {
var rise = this.y2 - this.y1;
var run = this.x2 - this.x1;
this.slope = rise / run;
return this.slope;
},
setIntercept : function(intercept) {
this.intercept = intercept;
},
getX : function(y) {
if (this.slope && this.intercept) {
if (this.slope && this.intercept) {
return (this.slope / y) - this.intercept;
}
}
},
getY : function(x) {
if (this.slope && this.intercept) {
return (this.slope * x) + this.intercept;
}
}
}
var anotherLine = {
x1: 3,
y1: 3,
x2: 6,
y2: 12
}
line.getSlope.call(anotherLine);
line.setIntercept.call(anotherLine, 3); // Which line gets modified?
line.getY.call(anotherLine, 100);
arguments
function addMany() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
addMany(0,55,100,0,200);
arguments
function addMany() {
this.total = 0;
for (var i = 0; i < arguments.length; i++) {
this.total += arguments[i];
}
return this.total;
}
someObject = {}
addMany.call(someObject,0,55,100,0,200);
function addMany() {
this.total = 0;
for (var i = 0; i < arguments.length; i++) {
this.total += arguments[i];
}
return this.total;
}
someObject = {}
someNumbers = [0,55,100,0,200]
addMany.apply(someObject,someNumbers);
Call
Apply
Maps parameters passed after the first one
Maps an array onto the parameters
function myFunction(p1, p2, p3) { ...
myFunction.call(someObj, 1, 2, 3)
function myFunction(p1, p2, p3) { ...
myFunction.apply(someObj, [1, 2, 3])
Bind returns a function with an explicit
this
var line = {
x1 : 0,
y1 : 0,
x2 : 2,
y2 : 2,
getSlope : function () {
var rise = this.y2 - this.y1;
var run = this.x2 - this.x1;
this.slope = rise / run;
return this.slope;
}
}
var line2 = { x1: 25, y1: 25, x2: 50, y2: 200 }
var getLine2Slope = line.getSlope.bind(line2)
console.log(getLine2Slope());
What's an execution context?
What's ?
this
What is the difference between call and apply?
What does bind return?