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

前端 未结 8 1257
半阙折子戏
半阙折子戏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 02:47

    The "global" scope of Javascript (at least in a browser) is the window object.

    This means that when you do this.myProperty = "foo" and call the function as plain myFunction() you're actually setting window.myProperty = "foo"

    The second point with myFunction().myProperty is that here you're looking at the return value of myFunction(), so naturally that won't have any properties as it returns null.

    What you're thinking of is this:

    function myFunction()
    {
        myFunction.myProperty = "foo";
    }
    
    myFunction();
    alert(myFunction.myProperty); // Alerts foo as expected
    

    This is (almost) the same as

    var myFunction = new Function('myFunction.myProperty = "foo";');
    myFunction();
    

    When you use it in the new context, then the "return value" is your new object and the "this" pointer changes to be your new object, so this works as you expect.

提交回复
热议问题