This article mainly introduces relevant information on the difference between ordinary functions and constructors in Javascript. Friends in need can refer to
The difference between ordinary functions and constructors
In terms of naming rules, constructors generally have the first letter capitalized, and ordinary functions follow the camel case naming method.
When the function is called:
function fn() { }
Constructor : 1. new fn( )
2. A new object will be created inside the constructor, that is, an instance of f
3. This inside the function points to the newly created instance of f
4. The default return value is the instance of f
Ordinary functions: 1. fn( )
2. No new objects will be created inside the calling function
3. This inside the function points to the object of the calling function ( If no object is called, the default is window)
4. The return value is determined by the return statement
The return value of the constructor:
There is a default return value, the newly created object ( Example);
When the return value is added manually (return statement):
1. The return value is a basic data type -->The real return value is still the newly created object (instance)
2. The return value is a complex data type (object)-->The real return value is this object
Look at a common interview question
<script> function foo() { var f2 = new foo2(); console.log(f2); //{a: 3} console.log(this); //window return true; } function foo2() { console.log(this); //foo2类型的对象 不是foo2函数 // this.age = 30; return {a: 3}; } var f1 = foo(); console.log(f1); // true </script>
The above is what I compiled for everyone, I hope it will be helpful to everyone in the future.
Related articles:
nodejs Detailed explanation of express implementation file upload case
JS generates a time list and outputs it
webpack.config.jsParameter usage case
The above is the detailed content of The difference between Javascript ordinary functions and constructors (detailed explanation combined with code). For more information, please follow other related articles on the PHP Chinese website!