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

后端 未结 6 1997
失恋的感觉
失恋的感觉 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
    慢半拍i (楼主)
    2020-11-27 19:54

    Short answer: not possible.

    This line of your code:

    var d = new c();
    

    automatically assumes that d is an object. Unless c is a constructor of a builtin object, e.g., Function. But if c is already defined by the language, you cannot manipulate its prototype, and cannot "inherit" it from whatever you like. Well, in some interpreters you can, but you cannot do it safely across all interpreters — the standard says: "you doth not mess with standard objects or the interpreter will smite you!".

    The builtin objects are "unique" and JavaScript does not provide ways to duplicate them. It is not possible to recreate String, Number, Function, and so on without resorting to incompatible trickery.

提交回复
热议问题