Created
August 7, 2015 03:24
-
-
Save jsdf/8588e2a1c0e03a20d553 to your computer and use it in GitHub Desktop.
Understanding 'this' in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A useful way of thinking about how the value of 'this' is bound in Javascript | |
// functions is to imagine that Function.prototype.call is being used | |
// implicitly at the call site to set the 'context' (the 'this' value). eg. | |
// assuming in each case | |
var o = {} | |
var o2 = {} | |
var fn = function(){} | |
// 1. bare function call | |
fn() // this == undefined in strict mode, global in non strict mode. | |
// 2. calling with Function.prototype.call | |
fn.call(o) // this == o | |
// 3. 'method' call (calling an object's function property) | |
o2.fn = fn | |
o2.fn() // this == o2 | |
// equivalent to | |
fn.call(o2) | |
// 4. calling object's function property with Function.prototype.call | |
o2.fn = fn | |
o2.fn.call(o) // this == o | |
// 5. new | |
var o3 = new fn() // this = o3 | |
// equivalent to | |
var o3 = Object.create(fn.prototype) | |
fn.call(o3) | |
// 6. calling function bound with Function.prototype.bind | |
var fn2 = fn.bind(o) | |
fn2() // this == o | |
// equivalent to | |
var fn2 = function(){ fn.call(o) } | |
fn2() | |
// 7. calling object function property which is a bound function | |
o2.fn = fn.bind(o) | |
o2.fn() // this == o | |
// equivalent to | |
o2.fn = function(){ fn.call(o) } | |
o2.fn() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment