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

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

    To answer your specific question, technically functions are always objects.

    For instance, you can always do this:

    function foo(){
      return 0;
    }
    foo.bar = 1;
    alert(foo.bar); // shows "1"
    

    Javascript functions behave somewhat like classes in other OOP languages when they make use of the this pointer. They can be instantiated as objects with the new keyword:

    function Foo(){
      this.bar = 1;
    }
    var foo = new Foo();
    alert(foo.bar); // shows "1"
    

    Now this mapping from other OOP languages to Javascript will fail quickly. For instance, there is actually no such thing as classes in Javascript - objects use a prototype chain for inheritance instead.

    if you're going to do any sort of significant programming in Javascript, I highly recommend Javascript: The Good Parts by Crockford, that guy you emailed.

提交回复
热议问题