Skip to content

Instantly share code, notes, and snippets.

@ltbringer
Last active March 6, 2017 13:40
Show Gist options
  • Save ltbringer/97a5381a9aa46c94d42577524ea90b28 to your computer and use it in GitHub Desktop.
Save ltbringer/97a5381a9aa46c94d42577524ea90b28 to your computer and use it in GitHub Desktop.
Using this in js
/**
* Use of this in js
*
* Unlike other languages, this works a bit differently in js
* A simple way to identify what is the value of this would be:
*
*/
function someConstructor () {
this.someProperty = 1
this.getThatProperty = function () {
return this.someProperty
}
}
var instance = new someConstructor ()
console.log(instance)
console.log(instance.getThatProperty())
/** notice how you can use this inside getThatProperty() method
* why:
* getThatProperty is a method on someConstructor,
* so the value of this will be the object calling the function.
*
* this.getThatProperty or instance.getThatProperty
* passes the context for this.
*/
// LESSON: this => object calling the function, if no object, this = window
var a = [1, 2, 3, 4]
a.map(function () {
console.log(this)
})
/** array.map is called by array, arrays are objects so why this didn't work?
* because the anonymous function is not being called by the array there is no '.' operator there!
*/
Array.prototype.test = function () {
console.log(this) // here this is the object calling the function so... Array
}
// Now test is a method that can be applied on all arrays
a.test() // this will print the same array!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment