I got confused about these two , var a = {} and var a = function(){}
a is an object in the first case , a is a function in the second case. And function is also a object. what is the difference?
A function is a type of an object in Javascript, but a empty function ( function(){}
) is very different from an empty object ( {}
). The easiest way to see the difference is to just execute them and see what they do differently. Using the console you can play around and see how they are different.
var emptyFunction = function() {} console.log(emptyFunction) // function(){} console.log(typeof emptyFunction) //"function" var emptyObject = {} console.log(emptyObject) //Object{} console.log(emptyObject) // "object" emptyFunction() // returns undefined because your function has no return emptyObject() // Uncaught TypeError: object is not a function
The first thing is the type of them are different things as the typeof
operator indicates. It shows you what Javascript thinks of the type The last line is where you really start to see the difference. A function is able to be invoked by using ()
to call it. An object does not have that ability and it will cause an error because the type Object doesn't have a behavior defined for it that involves using the ()
As you pointed out though, a function is just a specific type of object so it can do the same sort of things an object. So we can do something like this:
emptyFunction.foo = function(){ return 'foo';} console.log(emptyFunction.foo()) //'foo' emptyObject.bar = function(){ return 'bar';} console.log(emptyObject.bar()) //'bar'
As you can see when it comes down to it, the difference is a function is a specialized object that can be invoked. You can read more about functions in Javascript here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.