The difference between constructors and ordinary functions in JS

Source: Internet
Author: User
Tags naming convention

This introduction:
This always points to the owner of the function or method that is currently being executed. For example:

12345 functiontest(){  console.log(this);}test();//Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

In the above code, we define a test () function in the page and then call it in the page. When a function is defined globally, its owner is the current page, which is the Window object.

Here are a few things to point to

1. Calling in global

THIS.name//this pointing to the Window object

2. Function calls

Test (); The This in the//test () function also points to the Window object

3. Method invocation of the object

Obj1.fn (); The this point in the FN () method of the//obj1 object obj1

4. Calling constructors
var dog=new dog ();//The This in the constructor points to the newly created instance object, which is the Dogcall and apply

Call and apply have the same effect, just accept the parameters in a different way, call accepts a number of individual parameters, apply accepts the parameter array.
The function of call and apply can be simply said that when an object instance is missing a function/method, it can invoke the out-of-the-box function/method of other objects by replacing this object instance with this one, changing the context of the function runtime.
For example:

123456 functionDog(){  this.sound="汪汪汪";}Dog.prototype.bark=function(){  alert(this.sound);}

Now I have another cat object:

var cat={sound: ' Meow meow '}

I also want this cat object to call the Bark method, so you don't have to redefine the bark method for it, and you can call the bark method of the Dog class with call/apply:

Dog.prototype.bark.call (CAT);

Or:

Dog.bark.call (CAT);

Add something and become a chestnut with parameters:

123456789 function Dog(){  this.sound="汪汪汪";}Dog.prototype.bark=function(words){  alert(this.sound+" "+words);}var dog=new Dog();dog.bark("有小偷");//alert:汪汪汪  有小偷Dog.prototype.bark.call(cat,"饿了");//alert:喵喵喵  饿了

Common functions
This is a simple normal function:

1234 functionfn(){  alert("hello sheila");}fn();//alert:hello sheila

There are four distinct features compared to the normal function and the constructor function:

1. Do not need to call with the New keyword

FN ();

2. You can return a value using the return statement

1234 functionfn(a,b){   returna+b; } alert(fn(2,3));//alert:5

3. The This keyword is not recommended for use inside a function
We say that it is not recommended to use, of course, hard to use is possible, just to pay attention to what happened at this time. If you use the This keyword inside a normal function to define a variable or function, because this point is the window global object, you inadvertently add some global variables or functions to the window.

123456 functiongreeting(){    this.name="sheila";    alert("hello "+this.name);  }  greeting();//alert:hello sheila  alert(window.name);//alert:sheila

4. Function name in hump mode, first letter lowercase

constructor function
In JavaScript, use the new keyword to invoke the defined constructor. The default is to return a new object with the variables and functions/methods defined by the constructor.

As an example:

12345678910111213 function Prince(name,age){  this.gender="male";  this.kind=true;  this.rich=true;  this.name=name;  this.age=age;}Prince.prototype.toFrog=function(){  console.log("Prince "+this.name+" turned into a frog.");}var prince=new Prince("charming",25);prince.toFrog();//Prince charming turned into a frog.prince.kind;//true

Compared with the normal function, the constructor has the following obvious characteristics:

1. Call with the New keyword

var prince=new prince ("Charming", 25);

2. The This keyword can be used inside the function
Inside the constructor, this refers to the new object that is constructed. The variable or function/method defined with this is an instance variable or an instance function/method. You need to use an instance to access it, and you cannot access it with a type name.

Prince.age;//25
prince.age;//undefined

3. Return value is not returned by default
The constructor does not need to return the value explicitly, and the default is to return this, which is the new instance object. Of course, you can also use the return statement, the return value will vary according to the type of return value, details will be described below.

4. The function name is suggested to capitalize the first letter, separate from the normal function area.
Not in the naming convention, but it is recommended to write this.

What happens when I instantiate with the new keyword?
The Prince () function in the above article is an example:

1. The first step is to create an empty object.

var prince={}

2. In the second step, the this in the constructor Prince () points to the newly created object prince.
3. Step three, point the _proto_ attribute of the Prince to the prototype of the Prince function, and create the relationship between the object and the prototype
4. Fourth step, execute the code within the constructor prince ().

What if the constructor has a return value?
When return is not explicitly called in the constructor, the default is to return the This object, which is the newly created instance object.
When you call return in a constructor, there are two things:

1.return is the five simple data types: string,number,boolean,null,undefined.
In this case, the return value is ignored and the This object is still returned.

2.return is object.
In this case, the this object is no longer returned, but instead returns the return value of the return statement.

1234567 function Person(name){    this.name=name;    return {name:"cherry"}  }  var person=new Person("sheila");  person.name;//cherry  p;//Object {name: "cherry"}

The difference between constructors and ordinary functions in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.