// 1)
// Default binding
//
// Behaves like a catch-all
// Will use the global object
// However in strict mode, it will be undefined
var a=1;
// "this" is the global object, window
console.log("Window is this:", (this === window)); // true
console.log("Window.a is a", (window.a === a)); // true
function foo() { // new scope
console.log("This is window inside the function: ", this === window);
};
foo();
console.log("Function foo is on the window: ", foo === window.foo);
// 2)
// Implicit Binding
//
// When inside an object method
// the context is the container object itself
var myObject = {
sayHello: function () {
console.log("Hi! My name is " + this.myName);
// Warning: Inner function context is not the object
function innerFunction() {
console.log("Does inner have access to name?", this.myName);
}
innerFunction();
},
myName: "Rebecca"
};
// myObject is the context for sayHello
myObject.sayHello();
// you can copy functions around
var newObject = {myName : "Jim"};
newObject.sayHello = myObject.sayHello;
// newObject is the context for sayHello when invoked here
newObject.sayHello();
// 3)
// Explicit Binding
//
// All functions can have their context forced to something else
// using .call(), .apply()
console.group("Saying hello via call");
myObject.sayHello.call(newObject);
console.groupEnd();
// 4)
// Hard binding
//
// You can create a new function from an existing function
// and lock the binding to a specific context
console.group("Saying hello via bind");
var boundSayHello = myObject.sayHello.bind(newObject);
boundSayHello();
console.groupEnd();
// 5)
// new Binding
//
// When a function is used as a Constructor with "new" keyword
// a new object is created and set as the context
// for the constructor function
var MyConstructor = function(name) {
this.name = name;
}
var newObjectFromConstructor = new...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.