当前位置: 动力学知识库 > 问答 > 编程问答 >

In Javascript, is function foo() { } a class, a standard function, or a function with properties?

问题描述:

As a newbie, function foo() { } confuses me.

Why is it used with so many purposes? What is it built for? Doesn't this make maintenance of code difficult?

edit: I'm not talking about "foo" but about functions in general.

网友答案:

As I understand the question, you seem to be asking whether code is harder to maintain when functions are used for modules, functions, constructors, generators, and tons of other things. That's a fair question. Some may say yes, but many would say the language is simpler and more elegant because a single construct, the function, can do so much. It's no accident that Lisp and Smalltalk have some of the most passionate fans because those languages have a very simple core. JavaScript kind of has that simple core, but has a lot of other baggage, which you can read about in several places on the web.

But you also asked if a function was a class. Here's the deal: JavaScript does not have classes! It is best not to even think of classes in JavaScript. There are probably hundreds of attempts to create class-like structures in JavaScript. JavaScript was designed around the concept of delegation via prototypes.

Objects have prototypes. When you lookup a property in an object and the property is not present, the lookup is delegated to the prototype. That's it. Other languages like Self and Lua and Io have prototypes too (well Lua has metatables) but the point is: these languages don't have classes and they don't need them!

Now if you don't have classes and you want to make a bunch of objects of the same type, what do you do? You write a function that creates an object whose prototype holds the shared state and behavior for all the objects of that "type." Even in a language that has classes, the same kind of thing is going on---you have constructors (maybe called new or init or is named after the class or whatever).

Anyway, the answer to your question: "does not having classes make your program harder to maintain?" is "No, not when you learn how to use prototypes properly!"

It's ultimately a matter of preference, really. It is okay to prefer classes. It is okay to prefer prototypes. A good developer can use both.

网友答案:

As already stated in a comment, foo() is not an actual function. It is used to represent an example function. Function foo() can be anything else like f(), fun(), magic(), example().......You got the picture. When a funtion named foo() is used in working piece of code, it is made sure that the name is not used again. So it does not make maintenance difficult

分享给朋友:
您可能感兴趣的文章:
随机阅读: