Constructors in JavaScript objects

后端 未结 19 1720
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  无人及你
    2020-11-22 10:35

    In JavaScript the invocation type defines the behaviour of the function:

    • Direct invocation func()
    • Method invocation on an object obj.func()
    • Constructor invocation new func()
    • Indirect invocation func.call() or func.apply()

    The function is invoked as a constructor when calling using new operator:

    function Cat(name) {
       this.name = name;
    }
    Cat.prototype.getName = function() {
       return this.name;
    }
    
    var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
    

    Any instance or prototype object in JavaScript have a property constructor, which refers to the constructor function.

    Cat.prototype.constructor === Cat // => true
    myCat.constructor         === Cat // => true
    

    Check this post about constructor property.

提交回复
热议问题