Can JavaScript constructor return function and keep inheritance?

后端 未结 4 1000
滥情空心
滥情空心 2021-01-01 17:56
function F() {
    return function() {
        return {};
    }
}

var f = new F();
f instanceof F; // returns false

As far as I understand, if I w

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 18:37

    In you your example F is not a constructor it is a function that returns an anonymous constructor which you then call new upon. instanceof works by looking at the prototype chain, so your code doesn't work because you haven't setup up the prototypes correctly.

    This page has a good explain of JavaScript Constructors and how to subsclass.

    Take a look at the following code and see if it helps.

    function F() {
        this.whoami = 'F';
        this.whatami = 'F';
    
    }
    
    function Sub() {
     this.whoami = 'G';
    }
    
    Sub.prototype = new F();
    
    function G() {
        return new Sub;
    }
    
    var f = new G();
    console.log(f instanceof F); // returns false
    console.log(f.whoami);
    console.log(f.whatami);
    ​
    

提交回复
热议问题