this

JavaScript’s this always points to an object, which object is dynamically bound based on the context in which the function is executed, not the context in which the function is declared.

This point

Apart from the cases of with and eval, there are roughly four directions for this

  • Method invocation as an object
  • Called as a normal function
  • Constructor call
  • Function.prototype.call Function.prototype.applycall
Method invocation as an object

When a function is called as a method on an object, this refers to that object

var obj = {
    a: 1.getA: function(){
		alert(this === obj) // true
        alert(this.a) / / 1
    }
}

obj.getA()
Copy the code
Called as a normal function

When called as a normal function, this always points to a global object. In the browser, this global object is the Window object.

window.name = 'globalName'
var myObject = {
    name: 'sven'.getName: function(){
		return this.name
    }
}

var getName = myObject.getName
getName() // globalName
Copy the code
Constructor call

When a function is called with the new operator, the function always returns an object. Normally, this in the constructor refers to the object returned.

var MyClass = function(){
    this.name = 'sven'
}
var obj = new MyClass()
alert(obj.name) // sven
Copy the code
Function.prototype.call Function.prototype.applycall

The ability to dynamically change the this of the passed function compared to a normal function call

var obj1 = {
	name: 'sven'.getName: function(){
        return this.name
    }
}

var obj2 = {
	name: 'anne'
}

console.log(obj1.getName()) // sven
console.log(obj1.getName.call( obj2 )) // anne
Copy the code