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

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

提交回复
热议问题