The difference between the constructor and general functions

Constructor

Constructors: The function is used to initialize a (new operator) a new object, which we call the constructor (constructor)

Ordinary function

Common functions: do not use the new operator is an ordinary function

Constructor vs normal function

From the formal point of view, the only difference between a function is executed as a constructor or an ordinary function is whether to use the new

function Person(){
    this.name = "zqq"; this.age = 28; } var p = new Person(); 

When a new call to the constructor (executed var p = new Person ()), the internal function of the following occurs:

1. Create an empty object

var p = {};

2.this variable to point to the object p

Person.call(p)

3.p inherited constructor Person () prototype

p.__proto__ = Person.prototype

4. Person constructor is executed the code (in)

The difference between the constructor and general functions:

1. The constructor with the new keyword call; call a normal function without the new keyword;

var p = new Person();
var p = Person();

2. Internal constructors can use this keyword; internal normal function is not recommended to use this, because at that time this points to the window global object, among so will inadvertently added some global variables or functions for the window

2.1 在构造函数内部,this指向的是构造出来的新对象
2.2 在普通函数内部,this指向的是window全局对象 

3. return without default constructor return value; generally normal function return value is returned

3.1 构造函数会默认返回this,也就是新的实例对象

3.2 普通函数如果没有return值的话,返回undefined 3.3 如果使用了return,那返回值会根据return值的类型而有所不同 

<a href="https://segmentfault.com/a/1190000008472264"> involved here to understand the basic knowledge of data types and reference types of difference </a>

3.3.1 return的是五种简单数据类型:String,Number,Boolean,Null,Undefined的话,构造函数会忽略return的值,依然返回this对象;而普通函数会返回return后面的值 function Person(){ var a; this.name = "zqq"; this.age = 28; return a; } var p = new Person();//返回this对象 var p = Person();//因为a没初始化,所以a是undefined,而undefined属于简单数据类型,所以返回undefined,String,Number,Boolean,Null同理 3.3.2 如果return的是引用类型:Array,Date,Object,Function,RegExp,Error的话,构造函数和普通函数都会返回return后面的值 function Person(){ var arr = []; this.name = "zqq"; this.age = 28; return arr; } var p = new Person();//返回arr空数组,Date,Object,Function,RegExp,Error同理 var p1 = new Person();//返回arr空数组,Date,Object,Function,RegExp,Error同理 

4. constructor capitalized the first letter of recommendations; ordinary function lowercase first letter of recommendation



Guess you like

Origin www.cnblogs.com/newCoo/p/11266623.html