The most intuitive way to understand the difference between javascript constructors and ordinary functions

common problem zero five hundred and three

The way to distinguish a javascript function from a constructor or an ordinary function is to see which calling method they use. Whether a javascript constructor or a javascript ordinary function is a function, they are always functions. Their calling method determines whether they are constructors or ordinary functions.

 The most intuitive way to understand the difference between javascript constructors and ordinary functions

The following is the declaration of a function, which is a function, but the way it is used later determines whether it is a constructor or a normal function:

 function website(name,url){ this.webName = name; this.webUrl = url; }

Constructor

 Var site=new website ("resource sharing"“ http://www.aiyuanma.org/ "); site.webName; // resource sharing site.webUrl; // http://www.aiyuanma.org/

Call this function through the new operator, and this function is used as a constructor. That is, any function can be used as a constructor.

Ordinary function

 Website ("resource sharing"“ http://www.aiyuanma.org/ "); window.webName;// resource sharing window.webUrl; //  http://www.aiyuanma.org/

This function is used as a normal function. This points to the window object. That is to say, any function can be regarded as a normal function.

Summary:

  1. The difference between them is so simple. The new operator is used as a constructor, and other methods are used as ordinary functions;

  2. Any javascript function can be used as a constructor or a normal function

Message from netizens:

I would like to comment:

◎ Welcome to participate in the discussion. Please express your views and exchange your views here.
 Verification Code