Skip to content

Instantly share code, notes, and snippets.

@deanrad
Created January 25, 2014 19:08
Show Gist options
  • Save deanrad/8621766 to your computer and use it in GitHub Desktop.
Save deanrad/8621766 to your computer and use it in GitHub Desktop.
JS.Chi Explanation of Kangax Javascript Quiz problem #7 about the binding rules for 'this'
// JS.Chi Explanation of Kangax Javascript Quiz problem #7 about the binding rules for 'this'
// Dean Radcliffe, Deanius Solutions, Inc.
// www.deanius.com
// Presenter Setup: Split-screen browser/sublime, using JsRun to execute in chunks
console.clear();
/************** SEEING IT *****************/
//Gut check - what is 'this' in a browser by default ?
console.log("this: " + this);
//Problem #7
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
typeof (f=foo.bar)();
//What's the answer to problem #7?
console.log("typeof (f=foo.bar)(): " + typeof (f=foo.bar)());
/************** EXPLORING IT *****************/
//What would typeof (foo.bar)() been ?
console.log("typeof (foo.bar)(): " + typeof (foo.bar)())
//What went on ?
console.log("window.f: " + window.f)
//What was foo.bar?
console.log("foo.bar: " + foo.bar)
//Are they really the same object ?
console.log("window.f === foo.bar: " + (window.f === foo.bar));
//Yet why do they behave differently ?
console.log("window.f(): " + window.f());
console.log("foo.bar(): " + foo.bar());
//Check your resolution rules
//http://stackoverflow.com/questions/18963966/how-does-this-keyword-resolve-in-a-function-call
/************** 'FIXING' IT *****************/
//To ensure local resolution, we can close over self at create-time
function Foo(){
var self = this;
this.bar = function(){ return self.baz; };
this.baz = 1;
};
var foo = new Foo();
console.clear();
console.log("Foo= " + Foo.toString())
console.log("typeof (foo.bar)(): " + typeof (foo.bar)());
console.log("typeof (f=foo.bar)(): " + typeof (f=foo.bar)());
// But without 'new', be warned you will leak globals* !
var foo = Foo();
console.log("var foo = Foo(); // no 'new'!!");
console.log("window.baz: " + window.baz);
console.log("window.bar(): " + window.bar());
// * Unless 'use strict' mode is on, then only runtime errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment