Object vs Class vs Function

后端 未结 7 1023
南方客
南方客 2020-11-28 20:03

I was wondering - what\'s the difference between JavaScript objects, classes and functions? Am I right in thinking that classes and functions are types of objects?

A

7条回答
  •  一向
    一向 (楼主)
    2020-11-28 20:30

    JavaScript does not have classes, and functions are actually objects in JavaScript (first-class citizens). The only difference that function objects have is that they are callable.

    function func() { alert('foo'); } // a function - Correct

    func(); // call the function - alerts 'foo' - Correct

    var func2 = function () { alert('foo'); } // same as 'func' surely? - Nope, func2 is a different object, that apparently does the same thing when called.

    var Class = function() { alert('bar'); }; - It's a function with no name stored in variable Class.

    var c = new Class(); - Calls function stored in Class supplying new empty object as this and returning that object. Functions called as new functionA() are expected to work as constructors and prepare a newly created object (this). In your case - constructor does nothing with the object and just alerts bar.

提交回复
热议问题