What it the significance of the Javascript constructor property?

前端 未结 6 936
一生所求
一生所求 2020-11-22 04:23

Trying to bend by head around Javascript\'s take on OO...and, like many others, running into confusion about the constructor property. In particular, the signif

6条回答
  •  误落风尘
    2020-11-22 05:16

    The constructor property points to the constructor that was used to create the object instance. If you typed 'new Bar()' it will be 'Bar' and you typed 'new Foo()' it will be 'Foo'.

    But if you set the prototype without setting the constructor, you would get something like this:

    function Foo(age) {
        this.age = age;
    }
    
    function Bar() {
        this.name = "baz"; 
    }
    
    Bar.prototype = new Foo(42); 
    var one = new Bar();
    console.log(one.constructor);   // 'Foo'
    var two = new Foo();
    console.log(two.constructor);   // 'Foo'
    

    To set the constructor actually to the constructor that was used to create the object, we need to set the constructor as well while setting prototype as follows:

    function Foo(age) {
        this.age = age;
    }
    
    function Bar() {
        this.name = "baz"; 
    }
    
    Bar.prototype = new Foo(42); 
    Bar.prototype.constructor = Bar;
    var one = new Bar();
    console.log(one.constructor);   // 'Bar'
    var two = new Foo();
    console.log(two.constructor);   // 'Foo'
    

提交回复
热议问题