Home > Web Front-end > JS Tutorial > body text

The difference between Javascript ordinary functions and constructors

高洛峰
Release: 2016-12-07 15:34:46
Original
1267 people have browsed it

The difference between ordinary functions and constructors

In terms of naming rules, constructors generally have the first letter capitalized, while ordinary functions follow the camel case naming method. ​​​​​​​​3. This inside the function points to the newly created instance of f 4. The default return value is the instance of f

Ordinary function: 1. fn( )
2. No new object will be created inside the calling function

3. This inside the function points to the object calling the 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 (instance);
When the return value is added manually (return statement):


1. The return value is the basic data type -->The real return value is the newly created object (instance)
2. Return value It 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>
Copy after login



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!