How does the this keyword work? Provide some code examples

Technology CommunityCategory: JavaScriptHow does the this keyword work? Provide some code examples
VietMX Staff asked 3 years ago

In JavaScript this always refers to the “owner” of the function we’re executing, or rather, to the object that a function is a method of.

Consider:

function foo() {
	console.log( this.bar );
}

var bar = "global";

var obj1 = {
	bar: "obj1",
	foo: foo
};

var obj2 = {
	bar: "obj2"
};

foo();		 	// "global"
obj1.foo();	    // "obj1"
foo.call( obj2 );  // "obj2"
new foo();	     // undefined