Skip to content

Context

SimonPlanje edited this page Jun 21, 2020 · 1 revision

Context

Most simple example of context:

Windows is the default context in JavaScript.

console.log(this); in the global scope will give you back //Window. 

.this looks at the object/element where the scope refers to.

another simple example:

const = obj {
hello: function(){
console.log(this);
}
};

obj.hello();

this will become the property in which the function is being called. So in this case this === Object {hello: function}.

Three JavaScript methods for changing contexts

Call

const = obj {
hello: function(one, two, three){
console.log(this);
}
};

obj.hello.call(window, 1, 2, 3);

Apply

Apply is the same thing as call, but apply only takes two arguments. So the only thing that will changes is that the arguments you give has to be in an Array, but than it works exactly the same as call.

const = obj {
hello: function(one, two, three){
console.log(this);
}
};

obj.hello.apply(window, [1, 2, 3]);

Bind

Bind takes only one argument and does not actually run the function hello, but it returns a bound function so for example:

const = obj {
hello: function(one, two, three){
console.log(this);
}
};

let boundFunction = obj.hello.bind(window);
boundFunction();

Now boudnFunction is a function that always executes the function hello with a context of window. So this == Window while normally it would be like this this == Object {hello: function}.

Example with an click event:

const = obj {
hello: function(one, two, three){
console.log(this); //body
}
};

$('body').on('click', obj.hello;

Now when the body gets clicked the function hello will execute with an context of body.

The context only applies to the element that has been clicked on. So for example when you have a list of <li's> and you would click on the first li, the context will only be set to that certain li you clicked. This can be used to style or edit specific elements where the user interacts with.

<li> 1 </li>
<li> 2 </li>
<li> 3 </li>

Common problem

When there is a function declared inside another function and the this element is in that inner function, the context will link to this inner function.

$('body').on('click', function(){

$('li').anotherfunction(){
console.log(this); //li
}
}

This an easy way to get around this problem.

$('body').on('click', function(){
let self = this;
$('li').anotherfunction(){
console.log(self); //body
}
}

Now body will be logged because the variable this is not anymore in the inner scope.

Sources

Clone this wiki locally