Why in JavaScript is a function considered both a constructor and an object?

前端 未结 8 1215
半阙折子戏
半阙折子戏 2021-01-03 02:23

I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScr

8条回答
  •  孤城傲影
    2021-01-03 02:51

    Indeed, Functions are 'first class citizens': they are an Object.

    Every object has a Prototype, but only a function's prototype can be referenced directly. When new is called with a function object as argument, a new object is constructed using the function object's prototype as prototype, and this is set to the new object before the function is entered.

    So you could call every function a Constructor, even if it leaves this alone.

    There are very good tutorials out there on constructors, prototypes etc... Personally I learned a lot from Object Oriented Programming in JavaScript. It shows the equivalence of a function which 'inherits' its prototype, but uses this to fill in a new object's properties, and a function object that uses a specific prototype:

    function newA() { this.prop1 = "one"; } // constructs a function object called newA
    function newA_Too() {} // constructs a function object called newA_Too
    newA_Too.prototype.prop1 = "one";
    
    var A1 = new newA();
    var A2 = new newA_Too();
    // here A1 equals A2.
    

提交回复
热议问题