Can JavaScript constructor return function and keep inheritance?

后端 未结 4 940
滥情空心
滥情空心 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:23

    To anyone coming across this today, with ES6/2015 there's new syntax you can use to avoid the deprecated __proto__ property; Object.setPrototypeOf. Note that MDN warns that this is a slow/expensive operation.

    function F() {
        const f = function() {
            return {};
        }
        Object.setPrototypeOf(f, F.prototype);
        return f;
    }
    
    var f = new F();
    f instanceof F; // returns true
    f(); // returns {}
    

    Note also that it gets a little weird if you want to initialize values in the constructor. You need to set them as props on the function you will return, but later additions to the prototype will reference them as 'this'. e.g.

    function F() {
        const f = function() {
            return {};
        }
        f.favoriteBand = 'The Books';
        Object.setPrototypeOf(f, F.prototype);
        return f;
    }
    F.prototype.getFavoriteBand = function(){ return this.favoriteBand; }
    
    var f = new F();
    f.getFavoriteBand() // returns 'The Books'
    
    0 讨论(0)
  • 2021-01-01 18:24
    function F() {
        var r = function() {
            return {};
        };
    
        r.__proto__ = this.__proto__;
        return r;
    }
    
    var f = new F();
    f instanceof F;
    true
    f();
    Object
    

    Only works in the browsers with __proto__

    0 讨论(0)
  • 2021-01-01 18:29

    You could of course make all functions appear to be instanceof F by setting F.prototype = Function.prototype;.

    Unfortunately it looks as if ECMAScript doesn't allow you to create a function subclass.

    You can however do it in Gecko using the deprecated __proto__ property:

    function F() {
        function f() {
            return {};
        }
        f.__proto__ = F.prototype;
        return f;
     }
     F.prototype.__proto__ = F.__proto__;
    
    0 讨论(0)
  • 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);
    ​
    
    0 讨论(0)
提交回复
热议问题