Home > Web Front-end > Front-end Q&A > Can there be only one constructor in es6?

Can there be only one constructor in es6?

青灯夜游
Release: 2022-10-18 15:04:53
Original
2174 people have browsed it

Yes, each class can only have one constructor. If it contains multiple constructors, an exception will be thrown. The constructor is a special function that is mainly used to initialize objects, that is, assign initial values ​​to object member variables; two points should be noted when using the constructor: 1. The constructor is used to create a certain type of object, and its first letter must be capitalized ;2. The constructor only makes sense when used together with new.

Can there be only one constructor in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In typical OOP languages ​​(such as Java), there is the concept of class. A class is the template of an object, and the object is an instance of the class. However, before ES6, the concept of class was not introduced in JS. .

Before ES6, objects were not created based on classes. Instead, objects and their characteristics were defined using a special function called a constructor.

Objects can be created in the following three ways:

  • Object literal

  • new Object()

  • Custom constructor

// 1、利用 new Object() 创建对象
var obj1 = new Object();

// 2、利用对象字面量创建对象
var obj2 = {};

// 利用构造函数创建对象
function Star(name,age) {
    this.name=name;
    this.age=age;
    this.sing=function(){
        console.log('唱歌');
    }
}

var ldh=new Star('刘德华',23);
console.log(ldh);
ldh.sing();
// Star { name: '刘德华', age: 23, sing: [Function (anonymous)] }
//唱歌
Copy after login

Constructor

The constructor is a A special function, mainly used to initialize objects, that is, assign initial values ​​to object member variables. It is always used together with new. We can extract some public properties and methods from the object and encapsulate them into this function.

In JS, you should pay attention to the following two points when using constructors:

  • (1) The constructor is used to create a certain type of object, and its first letter must be capitalized

  • (2) The constructor only makes sense when used together with new

Each class can only have one constructor. If it contains multiple constructor, then an exception will be thrown

// 类的声明
class Person {
 // 类的构造方法 注:一个类只能有一个构造函数, 如果没有定义那就自动用默认的
 // 通过new关键字操作类的时候,会调用constructor函数,并执行如下操作
 // 1、在内存中创建一个对象 moni = {}
 // 2、 将类的原型prototype赋值给创建出来的对象 moni.__proto__ = Person.prototype
 // 3、将对象赋值给函数的this:new绑定 this = moni
 // 4、执行函数中的代码
 // 5、自动返回创建出来的对象
 constructor() {
 }
}
 
 
let p1 = new Person()
 
let P2 = new Person('kobe', 30)
Copy after login

new will do four things when executed:

(1) Create a new empty object in memory .

(2) Let this point to this new object.

(3) Execute the code in the constructor and add properties and methods to this new object.

(4) Return this new object (so no return is needed in the constructor).

Some members can be added to the JavaScript constructor, either on the constructor itself or on this inside the constructor. Members added through these two methods are called static members and instance members respectively.

  • Static members: Members added in the constructor are called static members and can only be accessed by the constructor itself

  • Instance members : The object members created inside the constructor are called instance members and can only be accessed by the instantiated object

For example:

// 构造函数中的属性和方法称为成员
function Star(uname, age) {
    this.uname = uname;
    this.age = age;
    this.sing = function() {
        console.log('我会唱歌');

    }
}
var ldh = new Star('刘德华', 18);

// 1、实例成员就是构造函数内部通过this添加的成员
// uname、age、sing就是实例成员
// 实例成员只能通过实例化的对象来访问
console.log(ldh.uname); //刘德华
ldh.sing();  //我会唱歌
// 不可以通过构造函数来访问实例成员
console.log(Star.uname); //undefined

Star.sex='男'
// 2、静态成员 在构造函数本身上添加的成员 sex 就是静态成员
// 静态成员只能通过构造函数来访问
console.log(Star.sex); //男
// 静态成员不能通过对象来访问
console.log(ldh.sex);  //undefined
Copy after login

Problems with constructors

The constructor method is easy to use, but there is a problem of wasting memory.

Can there be only one constructor in es6?

#We hope that all objects use the same function, which saves memory. So what should we do?

Constructor prototype prototype

Constructor The function assigned through the prototype is shared by all objects.

JavaScript stipulates that each constructor has a prototype property that points to another object. Note that this prototype is an object, and all properties and methods of this object will be owned by the constructor.

We can define those unchanged methods directly on the prototype object, so that all instances of the object can share these methods.

Print the properties of the object and view prototype

 function Star(uname, age) {
    this.uname = uname;
    this.age = age;
    this.sing = function() {
        console.log('我会唱歌');
    }
}
        console.dir(Star);
Copy after login

Output result:

Can there be only one constructor in es6?

  • What is the prototype?

An object, we also call prototype as the prototype object.

  • What is the function of prototype?

Shared method.

For example:

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
    // this.sing=function() {
    //     console.log('我会唱歌');
    // }
}
     Star.prototype.sing=function() {
         console.log('我会唱歌');
     }
    var ldh= new Star('刘德华',18);
    var zxy= new Star('张学友',19);
    console.log(ldh.sing===zxy.sing); //采用this添加方法时输出 false 采用prototype添加方法时输出 true
    ldh.sing();
    zxy.sing();
Copy after login

Object prototype__proto__

Every object will have an attribute __proto__ pointing to the constructor The prototype prototype object, the reason why our object can use the properties and methods of the constructor prototype prototype object, is because the object has the

__proto__ prototype.

__proto__Object prototype and prototype object prototype are equivalent

__proto__The significance of the object prototype is to provide a direction, or a route, for the object search mechanism, but it is a Non-standard attribute, so in actual development, this attribute cannot be used. It only internally points to the prototype object prototype

Can there be only one constructor in es6?

        function Star(uname, age) {
            this.uname = uname;
            this.age = age;
        }
        Star.prototype.sing=function(){
            console.log('我会唱歌');
        }
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
        console.log(ldh); 
        //对象身上系统自己添加一个__proto__ 指向构造函数的原型对象 prototype
        console.log(ldh.__proto__===Star.prototype); //true
        // 方法的查找规则(以sing方法为例):
        // 首先看 实例对象身上是否有 sing 方法,如果有就执行这个对象的sing
        // 如果没有sing 方法,因为有__proto__的存在,就去 构造函数原型对象prototype身上找sing 方法
Copy after login

Can there be only one constructor in es6?

constructor 构造函数

对象原型__proto__和构造函数(prototype)原型对象里面都有一个属性 constructor 属性 ,constructor 我们称为构造函数,因为它指回构造函数本身。

Can there be only one constructor in es6?

constructor 主要用于记录该对象引用于哪个构造函数,它可以让原型对象重新指向原来的构造函数。

一般情况下,对象的方法都在构造函数的原型对象中设置。如果有多个对象的方法,我们可以给原型对象采取对象形式赋值,但是这样就会覆盖构造函数原型对象原来的内容,这样修改后的原型对象 constructor 就不再指向当前构造函数了。此时,我们可以在修改后的原型对象中,添加一个 constructor 指向原来的构造函数。

   function Star(uname, age) {
            this.uname = uname;
            this.age = age;
        }
        Star.prototype = {
            // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指回原来的构造函数
            constructor: Star,
            sing: function() {
                console.log('我会唱歌');
            },
            movie: function() {
                console.log('我会演电影');
            }
        }
        var ldh = new Star('刘德华', 18);
        console.log(Star.prototype.constructor);
        console.log(ldh.__proto__.constructor);
Copy after login

Can there be only one constructor in es6?

给原型对象采取对象形式赋值,会覆盖构造函数原型对象原来的内容,就不会有constructor指向当前构造函数

        Star.prototype = {
            sing: function() {
                console.log('我会唱歌');
            },
            movie: function() {
                console.log('我会演电影');
            }
        }
      console.dir(Star);
Copy after login

Can there be only one constructor in es6?

解决办法:手动的利用constructor指回原来的构造函数

        Star.prototype = {
            // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指回原来的构造函数
            constructor: Star,
            sing: function() {
                console.log('我会唱歌');
            },
            movie: function() {
                console.log('我会演电影');
            }
        }
Copy after login

构造函数、实例、原型对象三者之间的关系

Can there be only one constructor in es6?

【相关推荐:javascript视频教程编程视频

The above is the detailed content of Can there be only one constructor in es6?. For more information, please follow other related articles on the PHP Chinese website!

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