Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Fundamentals of Javascript - function definition and "this"
// 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