Skip to content

Instantly share code, notes, and snippets.

@martinheidegger
Last active August 5, 2016 13:22
Show Gist options
  • Save martinheidegger/b5278928237b6744fcbd18aeddba7fc1 to your computer and use it in GitHub Desktop.
Save martinheidegger/b5278928237b6744fcbd18aeddba7fc1 to your computer and use it in GitHub Desktop.
Explaining methods and `this` at the NodeSchool Vienna #3. This is important, yet basic, JavaScript knowledge. With this way of method handling you should be able to understand callbacks more easily.
var method = function (someParam) {
console.log(this.propA + ' ' + someParam)
}
var objA = {
propA: 'foo:',
myMethod: method
}
var objB = {
propA: 'bar:',
myMethod: objA.myMethod // We could also use 'method', it is equal
}
console.log('#14')
objA.myMethod('X')
console.log('#16')
objB.myMethod('Y') // Depending on the object on which its called, the "this" of line 2 changes
var methodAsVariable = objA.myMethod // Its possible to reference any method as variable!
console.log('#21')
methodAsVariable('Z') // We can call this method but its 'this.propA' is not defined!
var someAPIMethod = function (callback) {
callback('response') // The API Method wants to call a callback.
}
console.log('#28')
someAPIMethod(function simpleCallback (param) {
console.log('simple callback: ' + param)
})
console.log('#33')
someAPIMethod(objA.myMethod)
console.log('#35')
someAPIMethod(methodAsVariable) // These two ways are equal. They will output 'undefined' because the methods lost their `this`
console.log('#38')
someAPIMethod(objA.myMethod.bind(objA)) // Now the method is bound to objA as it will output 'foo: response'
var objC = {
propA: 'baz:',
myMethod: objA.myMethod.bind(objA)
}
console.log('#46')
objC.myMethod('Oe') // Because myMethod is bound to objA, it will NOT take objC as 'this'
var methodX = objB.myMethod.bind(objB)
objB = null
console.log('#52')
methodX('works') // even thought the object has been freed from other references, it is still referenced in the method
methodX = null // this allows the former objB collected
#14
foo: X
#16
bar: Y
#21
undefined Z
#28
simple callback: response
#33
undefined response
#35
undefined response
#38
foo: response
#46
foo: Oe
#52
bar: works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment