Examples in Action: Using "this" with Functions

This example demonstrates a function invoked using call() and bind(). Understanding how these methods use this and what values they will assign is essential. Working through these examples will give you insight into the various values this can take on.

Example: A function invoked using Function.call
var myObject = {
sayHello : function() {
console.log('Hi! My name is ' + this.myName);
},
myName : 'Rebecca'
};
var secondObject = {
myName : 'Colin'
};
myObject.sayHello();                  // logs 'Hi! My name is Rebecca'
myObject.sayHello.call(secondObject); // logs 'Hi! My name is Colin'

Example A function created using Function.bind
var myName = 'the global object',
sayHello = function () {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
};
var myObjectHello = sayHello.bind(myObject);
sayHello();       // logs 'Hi! My name is the global object'
myObjectHello();  // logs 'Hi! My name is Rebecca'


Example: A function being attached to an object at runtime
var myName = 'the global object',
sayHello = function() {
console.log('Hi! My name is ' + this.myName);
},
myObject = {
myName : 'Rebecca'
},
secondObject = {
myName : 'Colin'
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello();               // logs 'Hi! My name is the global object'
myObject.sayHello();      // logs 'Hi! My name is Rebecca'
secondObject.sayHello();  // logs 'Hi! My name is Colin'

Source: Rebecca Murphey, https://autotelicum.github.io/Smooth-CoffeeScript/literate/js-intro.html#the-this-keyword
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License.

Last modified: Monday, September 11, 2023, 10:05 AM