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

前端 未结 8 1213
半阙折子戏
半阙折子戏 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:50

    Your understanding is wrong:

    myFunction().myProperty; // myFunction has no properties
    

    The reason it does not work is because ".myProperty" is applied to the returned value of "myFunction()", not to the object "myFunction". To wit:

    $ js
    js> function a() { this.b=1;return {b: 2};}
    js> a().b
    2
    js> 
    

    Remember, "()" is an operator. "myFunction" is not the same as "myFunction()". You don't need a "return" when instanciang with new:

    js> function a() { this.b=1;}
    js> d = new a();
    [object Object]
    js> d.b;
    1
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
提交回复
热议问题