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

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

    First, JavaScript doesn't behave the same way about objects as C++/Java does, so you need to throw those sorts of ideas out of the window to be able to understand how javascript works.

    When this line executes:

    var myFunctionVar = new myFunction();
    

    then the this inside of myFunction() refers to this new object you are creating - myFunctionVar. Thus this line of code:

     this.myProperty = "Am I an object!";
    

    essentially has the result of

     myFunctionVar.myProperty = "Am I an object!";
    

    It might help you to take a look at some documentation on the new operator. In JS, the new operator essentially allows you to create an object out of a function - any plain old function. There is nothing special about the function that you use with the new operator that marks it as a constructor, as it would be in C++ or Java. As the documentation says:

    Creating a user-defined object type requires two steps:

    1. Define the object type by writing a function.
    2. Create an instance of the object with new.

    So what you have done with the code

    function myFunction(){
        this.myProperty = "Am I an object!";
    }
    

    is to create a function that would be useful as a constructor. The reason why the code myFunction.myProperty fails is that there is no reference named myFunction.

提交回复
热议问题