Learn from me about javascript's function calls and constructor calls

  • 2020-10-31 21:39:25
  • OfStack

1. Function call
Function is definitely a top priority in JavaScript. In JavaScript, Function takes on the functions of procedures, methods, constructors and even classes and modules.

In object-oriented programming, functions, methods, and class constructor tend to be three different things, implemented by different grammars. But in JavaScript, all three concepts are implemented by function through three different modes.

The simplest mode of use is the function call:


function hello(username) { 
  return "hello, " + username; 
} 
hello("Keyser Söze"); // "hello, Keyser Söze" 

2. Method invocation

The representation of methods 1 in JavaScript is that the properties of an object are 1 function: the same is true for functions that assign values to members of an object. When a function is assigned to a member of an object, it is no longer called a function, but a method.


var obj = { 
  hello: function() { 
    return "hello, " + this.username; 
  }, 
  username: "Hans Gruber" 
}; 
obj.hello(); // "hello, Hans Gruber" 

The real behavior is that the call itself determines which object this is bound to, that is:
obj1.hello () will bind this to obj1, and ES39en2.hello () will bind this to obj2. Remember that this points to whoever calls it

Because of this rule of this binding, the following usage is also possible:


function hello() { 
  return "hello, " + this.username; 
} 

var obj1 = { 
  hello: hello, 
  username: "Gordon Gekko" 
}; 
obj1.hello(); // "hello, Gordon Gekko" 

var obj2 = { 
  hello: hello, 
  username: "Biff Tannen" 
};_ 
obj2.hello(); // "hello, Biff Tannen" 

However, in a normal function such as the hello function above, using the this keyword is not a good way to do it, and when it is called directly, the pointing of this becomes a problem. In this case, this is often referred to as a global object (GlobalObject), which in the browser is typically an window object.
And this kind of behavior is uncertain and meaningless.

Therefore, in the ES5 standard, if strict mode is used, THEN this will be set to undefined:


function hello() { 
  "use strict"; 
  return "hello, " + this.username; 
} 
hello(); // error: cannot read property "username" of undefined 

This approach is designed to allow potential errors to be exposed more quickly, avoiding misoperation and hard-to-find bug.
The difference between a normal function call and a method call is made clear by looking directly at this example.


var func = function() {
  alert(this);
};
var o = {};
o.fn = func;
//  To compare 
alert(o.fn === func);//true
//  call 
func();//[object Window]
o.fn();//[object Object]

The result of the run here is that the two functions are identical, so the print result is true. But because the two function calls are not the same, the call to func prints [object Window] and the print result of o.fn prints [object Object].

Here is the difference between function calls, where this refers to the global object window, and method calls, where this refers to the current object, o.fn refers to the object o.

3. Constructor call

The third usage pattern of function is to refer to it as constructor:

this in the constructor

We need to analyze the process of object creation to know the meaning of this, as follows:


 var Person = function() {
  this.name = " Small pingguo ";
 };
 var p = new Person();

Here, the function Person is defined first, and the whole execution is analyzed below:

The program does not execute the body of the function until this sentence is executed, so the JavaScript interpreter does not know the contents of the function. Next, the new keyword is executed, the object is created, the interpreter opens the memory, the reference to the object is obtained, and the reference to the new object is given to the function. The function then executes, passing the object reference to this. That is, in the constructor, this is the object that new just created. Then add members for this, that is, add members for the object. At the end of the function, this is returned, handing this to the variable on the left.

After analyzing the execution of the constructor, you can see that this in the constructor is the current object.

return in the constructor

The meaning of return changes in the constructor, first of all if in the constructor, if an object is returned, then the original meaning is retained. Returns this if it returns a non-object such as a number, Boolean, and string, and this if it does not have an return statement. Look at the code below:


 //  return 1 An object of  return
 var ctr = function() {
  this.name = " Zhao Xiaohu ";
  return {
  name:" Cattle deleterious "
  };
 };
 //  Create an object 
 var p = new ctr();
 //  access name attribute 
 alert(p.name);

 // Execute the code, and the result printed here is " Cattle deleterious ".  Because what's returned in the constructor is 1 Object, then keep return The meaning of, returns the content as return Subsequent objects .  Consider the following code: 

 //  Defines a constructor that returns non-object data 
 var ctr = function() {
  this.name = " Zhao Xiaohu ";
  return " Cattle deleterious ";
 };
 //  Create an object 
 var p = new ctr();
 //  use 
 alert(p);
 alert(p.name);

The result of the code operation is that the popover is printed first [object Object] and then "Zhao Xiaohu" is printed. Since return is a string of the basic type, the return statement here is invalid and returns an this object. So the first one prints [object Object] and the second one doesn't print undefined.


function User(name, passwordHash) { 
  this.name = name; 
  this.passwordHash = passwordHash; 
} 
var u = new User("sfalken", 
  "0ef33ae791068ec64b502d6cb0191387"); 
u.name; // "sfalken" 

Using the new key, function is called as constructor. Unlike function and method calls, constructor passes in a new object, binds it to this, and returns the object as the return value of constructor. The purpose of constructor function itself is to initialize this object.

A common error made by constructor calls

The following constructor is defined with gusto:


var Coder = function( nick ){ 
this.nick = nick; 
}; 

What happens when the constructor is defined? That's right, instantiate:


var coder = Coder( 'casper' ); 

What is the name of this coder brother? Print it quickly:


var obj = { 
  hello: function() { 
    return "hello, " + this.username; 
  }, 
  username: "Hans Gruber" 
}; 
obj.hello(); // "hello, Hans Gruber" 
0

This kind of mistake seems to be quite low-level, but the probability of occurrence is quite high, how to avoid or reduce the occurrence of this kind of situation?
You can do things inside:


var obj = { 
  hello: function() { 
    return "hello, " + this.username; 
  }, 
  username: "Hans Gruber" 
}; 
obj.hello(); // "hello, Hans Gruber" 
1

In fact, it is very simple, when instantiating, internally, this points to the type of the object, if not the current constructor type, forced to re-call the constructor 1.
Suddenly the name Coder isn't western enough? I want to use Hacker, ok, I'll change to... I've counted 3 changes in 1, it's not scientific, is there a way to just change the name of the constructor?
Of course, there are:


var obj = { 
  hello: function() { 
    return "hello, " + this.username; 
  }, 
  username: "Hans Gruber" 
}; 
obj.hello(); // "hello, Hans Gruber" 
2

tips: It is said that arguments.callee will be disabled under the strict mode of ES 5, but only if ES 5 becomes popular and you specify to use the strict mode, otherwise you can still use divergent thinking.

That's it for this article, and I hope it helps you learn about function calls, method calls, and constructor calls.


Related articles: