开发者

Is JavaScript function a "function" or an "object" or both?

I am tryin开发者_如何学Gog to get my head around how Javascript function behaves. Is it a function or an object or both?


Functions in javascript are first-class objects. So they're both functions and objects.

Because they are first class objects, you can assign a variable to a function and give it properties, eg:

var addName=function(){}; 
addName.blah = 1;

If they weren't first-class objects you'd be limited to this syntax but you can do it both ways:

function addName(){}


It is both.

Everything is "data" in Javascript, including functions. I find this a good way to picture it:

var f = function() { alert('foo'); };

This is an assignment to a variable that's no different than if you'd written, say:

var f = new String('foo');

Either way, you can then write statements like f.bar = 'baz'; to assign properties to your object. The only difference is that the () operator (if you will) works only if the variable you have happens to be a function. f() makes sense if it's a function; f() makes no sense if it's a string or some other piece of data.


In JavaScript all functions are objects.

Functions are objects that can be called. (They have a internal [[Call]] property)


Well, I'm not going to say "JavaScript functions are objects of first class", since everyone already said that, but if you want more on functions, take a look at this short page:

http://jqfundamentals.com/book/ch02s09.html

By the way, if you're planning on learning JavaScript and JQuery, that's a free online book for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜