JavaScript Function Context

by Wentz Wu

HTML

<h1>call, apply, and bind</h1>
<ul>
  <li>'call' passes parameters individually while 'apply' passes parameters using an array;</li>
  <li>'bind' change the function context as well but doesn't invoke the function immediately.</li>
</ul>

<h1><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" target="_blank">The context for 'this'</a></h1>
<ul>
  <li>Using call to chain constructors for an object</li>
  <li>Using call to invoke an anonymous function</li>
  <li>Using call to invoke a function and specifying the context for 'this'</li>
</ul>

<div id="result"></div>

JavaScript

var friend = new Friend("Jack", 20);

var msg = Greet.call(friend);

var msg2 = (function Greet(msg) {
  return msg + " " + this.name;
}).call(friend, "Hello!");

print(friend.name + " is " + friend.age + "\r" + msg + "\r" + msg2);

/* chain constructors */
function Person(name) {
  this.name = name;
}

function Friend(name, age) {
  Person.call(this, name);
  this.age = age;
}

/* specifying the context for 'this' */
function Greet() {
  var msg = "Hi! " + this.name;
  return msg;
}

function print(msg) {
  var result = document.getElementById("result");
  result.innerText = msg;
}