I want to learn about javascript Functions and constructor calls in three aspects: function calls, method calls, and constructor calls. Do not miss the following content if you want to know the content.
I. function call
Function is definitely the top priority in JavaScript. In JavaScript, the Function functions include procedures, methods, constructors, and even classes and modules.
In object-oriented programming, functions, methods, and class constructor are usually three different things implemented by different syntaxes. However, in JavaScript, all three concepts are implemented by functions through three different modes.
The simplest use mode is function call:
function hello(username) { return "hello, " + username; } hello("Keyser Söze"); // "hello, Keyser Söze"
Ii. Call Methods
The concept of methods in JavaScript is that the attribute of an object is a function, which is also a function. After assigning a function to a member of an object, it will be different. After assigning a function to a member of an object, this is not 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 the object to which this will be bound, namely:
Obj1.hello () binds this to obj1, and obj2.hello () binds this to obj2. Remember one sentence. Whoever calls this will point to WHO
This is because this binding rule is also feasible in the following usage:
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 common function, using the this keyword for the preceding hello function is not a good method. When it is directly called, the point of this becomes a problem. In this case, this is usually directed to a global object, which is generally a window object in a browser.
Such behavior is uncertain and meaningless.
Therefore, if strict mode is used in ES5, this will be set to undefined:
function hello() { "use strict"; return "hello, " + this.username; } hello(); // error: cannot read property "username" of undefined
The above practice aims to expose potential errors more quickly and avoid misoperations and hard-to-find bugs.
The difference between a common function call and a method call is clear in this example.
Var func = function () {alert (this) ;}; var o ={}; o. fn = func; // compare alert (o. fn = func); // true // call func (); // [object Window] o. fn (); // [object Object]
The running result here is that the two functions are the same, so the printed result is true. However, because the call of the two functions is different, the call of func prints [object Window], while the result of o. fn is [object Object object].
This is the difference between function call and method call. In function call, this refers to the Global Object window, while in method, this refers to the current object, that is, o. this In fn refers to object o.
Iii. Call of Constructor
The third usage mode of a function is to use it as a constructor:
This in the constructor
We need to analyze the process of object creation to understand the meaning of this, as shown in the following code:
Var Person = function () {this. name = "Xiao Pingguo" ;}; var p = new Person ();
The Person function is defined first. The execution is analyzed as follows:
- When the program executes this sentence, it will not execute the function body, so the JavaScript interpreter does not know the content of this function.
- Next, execute the new Keyword, create an object, open the memory in the interpreter, get the object reference, and hand over the reference of the new object to the function.
- Then execute the function and assign the passed object reference to this. That is to say, in the constructor, this is the object just created by new.
- Then add a Member for this, that is, add a member for the object.
- When the function ends, this is returned, and this is handed over to the variable on the left.
After the execution of the constructor is analyzed, we can see that this in the constructor is the current object.
Return in Constructor
The meaning of return changes in the constructor. First, if an object is returned in the constructor, the original intent is retained. if the returned result is a non-object, such as a number, Boolean, or string, this is returned. If no return statement exists, this is returned. see the following code:
// Return the return var ctr = function () {this. name = "Zhao Xiaohu"; return {name: "niu Liangliang" };}; // create an object var p = new ctr (); // access the name attribute alert (p. name); // run the code. The result is "niu Liangliang ". because the constructor returns an object, the meaning of return is retained, and the returned content is the object after return. look at the following code: // defines the constructor var ctr = function () {this. name = "Zhao Xiaohu"; return "niu Liangliang" ;}; // create the object var p = new ctr (); // use alert (p); alert (p. name );
The code execution result is that the [object Object] is printed in a pop-up window, and then "Zhao Xiaohu" is printed ". because the return is a string of the basic type, the return statement here is invalid and the return is the this object. therefore, the first print is [object Object], and the second won't print undefined.
function User(name, passwordHash) { this.name = name; this.passwordHash = passwordHash; } var u = new User("sfalken", "0ef33ae791068ec64b502d6cb0191387"); u.name; // "sfalken"
Use the new key to call the function as a constructor. Unlike function and method calls, constructor will pass in a new object and bind it to this, and then return this object as the return value of constructor. The function of constructor is used to initialize the object.
A common error in constructor calls
Happily defined the following constructor:
var Coder = function( nick ){ this.nick = nick; };
After the constructor is defined? That's right. instantiate it quickly:
var coder = Coder( 'casper' );
What is the name of the coder brother? Print the following:
Console. log (coder. nick); // undefined = B is undefined !! Looking back at the instantiated statement, it is not difficult to find out where the problem is: missing a new var coder = Coder ('casper '); // called as a common function, therefore, the internal this pointer actually points to the window object console. log (window. nick); // output: casper var coder = new Coder ('casper '); // when new is added, everything is different. this correctly points to the console of the currently created instance. log (coder. nick); // output: casper
This kind of error seems quite low-level, but the probability of occurrence is quite high. Is it possible to avoid or reduce the occurrence of this situation?
You can move your hands and feet in the internal implementation:
var Coder = function( nick ){ if( !(this instanceof Coder) ){ return new Coder( nick ); } this.nick = nick; };
In fact, it is very simple. During the instantiation, We can internally determine the type of the object to which this currently points. If it is not the type of the current constructor, the constructor is forced to be called again.
Suddenly I think Coder is not a good name? I want to use Hacker... There are three changes to the number. This is not scientific. Is there a way to change the name of the constructor?
Of course:
var Coder = function( nick ){ if( !(this instanceof arguments.callee) ){ return new arguments.callee( nick ); } this.nick = nick; };
Tips: It is said that arguments is in the strict mode of ES 5. callee will be disabled, but if elasticsearch 5 is popular and you specify a strict mode, you can still use divergent thinking.
The above is all the content in this article. I hope it will be helpful for you to learn about function calls, method calls, and constructor calls.