JavaScript four call modes and this example is introduced

  • 2020-03-30 01:10:16
  • OfStack

JavaScript calls each function with two additional arguments, this and arguments, in addition to the parameters defined at declaration time. This is very important in object-oriented programming and depends on the invocation mode.

JavaScript has four call modes: method call mode, function call mode, constructor call mode, and apply call mode. These modes differ in initializing the key parameter this.

Method call pattern: when a function is saved as a property of an object, we call it a method, and when a method is called, this is bound to the object. If the calling expression contains a property fetch expression (that is, a dot expression or a [script] subscript expression), it is treated as a method call.
var myObject = { 
value: 0; 
increment: function(inc){ 
this.value += typeof inc === 'number' ? inc : 1; 



Method can use this to access an object, so it can value or modify objects from an object. The binding of this occurs when invoked. This super late binding allows the function to reuse this height. The contextual methods to which they belong are called public methods.

Function call pattern: when a function is not a property of an object, it is called as a function, var sum = add(3, 4); / / the sum value of 7
This is bound to a global object when the function is called in this mode.

Constructor invocation pattern: JavaScript is a language based on prototype inheritance. This means that properties can be inherited directly from other objects. The language is categorical.
If called with new in front of the function, a new object is created that hides the connection to the function's prototype member, and this is bound to that new object.

Apply invocation pattern: because JavaScript is a functional object-oriented programming language, functions can have methods.
The apply method lets us build an array of arguments and use it to call the function. It also allows us to select the value of this.
The apply method takes two arguments, the first to be bound to the value of this, and the second to be an array of arguments.

Related articles: