Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the context of a function in javascript

Tags:

I'm trying to understand why in javascript, you might want to change the context of a function. I'm looking for a real world example or something which will help me understand how / why this technique is used and what its significance is.

The technique is illustrated using this example (from http://ejohn.org/apps/learn/#25)

var object = {};  function fn(){    return this;  }  assert( fn() == this, "The context is the global object." );  assert( fn.call(object) == object, "The context is changed to a specific object." ); 
like image 812
32423hjh32423 Avatar asked Oct 08 '09 07:10

32423hjh32423


People also ask

How do you change the context of a given function in JavaScript?

var object = {}; function fn(){ return this; } assert( fn() == this, "The context is the global object." ); assert( fn. call(object) == object, "The context is changed to a specific object."

How can you call a function and assign the this context to an object?

call() and . apply() methods allow you to set the context for a function.

What is function context in JavaScript?

Context in JavaScript is related to objects. It refers to the object within the function being executed. this refers to the object that the function is executing in.

Can you reassign this JavaScript?

In JavaScript, we can simply reassign the new value to the variable. When we change the value of a variable, we do not use var again. We simply use the = to give the variable a new value.


2 Answers

jQuery makes use of it to good effect:

$('a').each(function() {     // "this" is an a element - very useful }); 

The actual jQuery code looks like this:

for ( name in object ) {     if ( callback.call( object[ name ], name, object[ name ] ) === false ) {         break;     } } 

If it just did callback( name, object[ name ] ) then this wouldn't be set to the current object in your iterator and you'd have to use the parameter instead. Basically it just makes things easier.

like image 118
Greg Avatar answered Sep 20 '22 03:09

Greg


Please have a look at this example:

<script> var el = document.getElementById('button'); el.onclick = function(){     this.value = "Press Me Again"; //this --> now refers to the the element button not on the window }  //Another Example: var Person = function(name,location){   this.name = name;   this.location = location;     alert(this.location);  }    var p2 = new Person("Samantha","California"); //this refers to the instance of the function Person(Person now acts as a class) var p1 = Person(); // this refers to the window(Person simply acts as a simple function) </script> <button id="button1">Press Me</button> 

The new keyword changes the context.

like image 45
jerjer Avatar answered Sep 18 '22 03:09

jerjer