Home>

Learn with me JavaScript function and constructor calls,It mainly includes three aspects:function call, method call, and constructor call.Friends who want to know these contents should not miss the following content.

First, the function call

function is definitely the top priority in JavaScript.In JavaScript, functions assume the functions of procedures, methods, constructors, and even classes and modules.

In object-oriented programming,Functions, methods, and class constructors are often three different things.Implemented by different syntax.But in JavaScript, these three concepts are implemented by functions, through three different modes.

The simplest usage pattern is a function call:

function hello (username) {
  return "hello," + username;
}
hello ("keyser söze");//"hello, keyser söze"

Second, the method call

The expression of the concept of methods in javascript is,The property of an object is a function:the same is a function,After assigning it to a member of an object,It's different.After assigning a function to a member of an object,Then this is no longer called a function,It should be called a method.

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

The real behavior is,The call itself determines which object this is bound to,which is:

obj1.hello () will bind this to obj1, and obj2.hello () will bind this to obj2. Remember a word,Whoever calls this points to

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,Like the hello function above, using the this keyword is not a good way,When it is called directly,The pointing of this becomes a problem.under these circumstances,This is often referred to as the global object, which is usually the window object on the browser.

And this behavior is uncertain and meaningless.

So 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

The above approach is to allow potential errors to be exposed more quickly,Avoid misoperations and hard-to-find bugs.

Distinguish between ordinary function calls and method calls,Just look at this example to make it clear.

var func=function () {
  alert (this);
};
var o=();
o.fn=func;
//compare
alert (o.fn === func);//true
//transfer
func ();//[object window]
o.fn ();//[object object]

The result here is,Both functions are the same,So the print result is true. But because the two functions are called differently,The call of func prints [object window], and the print result of o.fn is [object object].

Here is the difference between a function call and a method call,During the function call,this refers to the global object window, while in methods this refers to the current object,That is, this in o.fn refers to object o.

Third, the constructor call

The third mode of use of function is to refer to it as a constructor:

This in the constructor

We need to analyze the process of creating objects,Only then can we know the meaning of this. Such as the following code:

var person=function () {
  this.name="Xiaopingguo";
 };
 var p=new person ();

The function person is first defined here, and the entire execution is analyzed below:

When the program reaches this sentence,Does not execute the function body,So the JavaScript interpreter doesn't know the content of this function. Next execute the new keyword to create the object,The interpreter opens up memory,Get a reference to the object,Pass a reference to the new object to the function. Immediately after executing the function,Pass the passed object reference to this. That is,In the constructor,This is the object just created by new. Then add members for this,That is, adding members to the object. Finally the function ends,Returns this, passing this to the variable on the left.

After analyzing the execution of the constructor,Can be obtained,This in the constructor is the current object.

Return in the constructor

The meaning of return has changed in the constructor,First if in the constructor,If an object is returned,Then keep the original intent. If a non-object is returned,Like numbers, booleans and strings,Then return this, if there is no return statement, then also return this. See the following code:

//return an object
 var ctr=function () {
  this.name="Zhao Xiaohu";
  return {
  name:"Niu Liangliang"
  };
 };
 //create object
 var p=new ctr ();
 //access the name attribute
 alert (p.name);
 //execute the code,The result printed here is "Niu Liangliang". Because the constructor returns an object,Then the meaning of return is retained, and the returned content is the object after return.
 Look at the following code:
 //Define a constructor that returns non-object data
 var ctr=function () {
  this.name="Zhao Xiaohu";
  return "Niu Liangliang";
 };
 //create object
 var p=new ctr ();
 //use
 alert (p);
 alert (p.name);

The result of running the code is,First pop up the window and print [object object], then print "Zhao Xiaohu". Because return here is a stringBelongs to the basic type,Then the return statement here is invalid,The this object is returned. So the first one prints [object object] and the second one does not 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 function as a constructor.Unlike function and method calls,The constructor takes a new object and binds it to this, and then returns that object as the return value of the constructor.The role of the constructor function is to initialize the object.

A common mistake in constructor calls

The following constructor is happily defined:

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

After defining the constructor?Yes, instantiate it:

var coder=coder ("casper");

What's the name of this coder brother?Quickly print:

console.log (coder.nick);//undefined
==b turned out to be undefined! !! Looking back at the instantiated statement,It is not difficult to find out where the problem lies:a new one is missing
var coder=coder ("casper");//Called as a normal function,So the internal this pointer actually points to the window object
console.log (window.nick);//Output:casper
var coder=new coder ("casper");//Add new, everything is different,this correctly points to the currently created instance
console.log (coder.nick);//Output:casper

This error looks very low-level,But the probability of occurrence is quite high,Is it swollen to avoid or reduce this situation?

You can tamper with the internal implementation:

var coder=function (nick) {
  if (! (this instanceof coder)) {
    return new coder (nick);
  }
    this.nick=nick;
};

it's actually really easy,When instantiated,In internal judgment,The type of the object this currently points to,If not the type of the current constructor,Force the constructor to be called again.

Suddenly feel that the name coder is not foreign enough?I want to use a hacker, well, I changed. . . Counted, there are three changes to be made,This unscientific,Is there a way to just 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.callee will be disabled in strict mode of es 5,But only when es 5 becomes popular and you specify that i want to use strict mode,Otherwise, you can still use divergent thinking.

  • Previous Android programming method to add pictures and text to Button
  • Next The operating mechanism and principle of PHP (bottom)