Can a JavaScript object have a prototype chain, but also be a function?

后端 未结 6 1987
失恋的感觉
失恋的感觉 2020-11-27 19:20
function a () {
    return \"foo\";
}

a.b = function () {
    return \"bar\";
}

function c () { };
c.prototype = a;

var d = new c();
d.b(); // returns \"bar\"
d()         


        
6条回答
  •  萌比男神i
    2020-11-27 19:52

    Does it have to actually be a prototype chain? You can use a mixin pattern to make a function have all of the properties of a instead. You can even wrap it in a nice "new" syntax to fake it if you really want.

    function a () {
        return "foo";
    }
    
    a.b = function () {
        return "bar";
    }
    
    function c () {
        var f = function(){
            return a();
        };
    
        //mixin all properties on a
        for(var prop in a){
            f[prop] = a[prop];
        }
    
        return f; //just returns the function instead of "this"
    };
    
    var d = new c(); //doesn't need the new keyword, but just for fun it still works
    
    alert(d()); //show "foo"
    
    alert(d.b()); //shows "bar"
    

    You can add properties to d without affecting a. The only difference between this and what you want is that changes to a will not affect existing "instances" of c.

提交回复
热议问题