this

JacaScript’s This always points to an object that is dynamically bound at runtime based on the execution environment of the function, not the environment in which the function is declared.

1. Methods called as objects

When a function is called as a method of an object, this refers to the object:

var obj = { a:1, getA:function(){ alert(this === obj); // Output :true alert(this.a); // Output :1}}; obj.getA();Copy the code

2. Called as a normal function

When a function is not called as a property of an object, this is what we call normal function mode. This always refers to the global object. In browser JavaScript, this global object is the Window object.

window.name = 'globalName'; var getName = function(){ return this.name; } console.log(getName()); / / output: globalNameCopy the code

3. Constructor calls

There are no classes in JavaScript, but objects can be created from constructors, and the new operator is provided to make the constructor look more like a class.