Last active
August 29, 2015 13:57
-
-
Save alvinang/9363089 to your computer and use it in GitHub Desktop.
Fundamentals of Javascript - function definition and "this"
This file contains 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
// IMPORTANT: "this" is set when a function is CALLED, not defined. | |
// It also depends on how it is called. | |
// There are 4 ways to define a function (directly affect "this" as well) | |
// 1. Constructor | |
// "this" -> new object {} | |
var func = new User(); | |
// 2. Method | |
// "this" -> receiver (func) | |
obj.method(); | |
// 3. Functional | |
// "this" -> global namespace / window | |
var myFunc = clock.run; | |
myFunc(); | |
// 4. Call/Apply | |
// "this" -> first argument (obj) | |
func.call(obj); | |
// After understanding what "this" is, often times, there will be errors when calling "this" within another method. | |
// Two ways to handle this: | |
// 1. Bind -> "this" will refer to obj. Often times, we have to use add append "this". i.e. this.func.bind(obj); | |
func.bind(obj); | |
// 2. Create anonymous function & use var that = this; | |
// instead of setInterval(this.tick, 5000) - as this is a functional, hence "this" is windows | |
var that = this; | |
setInterval(function () { | |
that.tick(); | |
}, 5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment