Js object-oriented design: {} is good or function () {} is good. You have replied and I feel good. I would like to share it with you. I have read many JavaScript projects on the Internet, and the objects used are in the form:
For example, jQuery and TinyMCE all have the following shapes:
The Code is as follows:
Var Dialog =
{
Int: function (){....},
Insert: function (){....},
Pop: function (){....}
};
// The call is:
Dialog. init ();
I have always used function closures, and I feel it is more convenient to use internal private members (functions and variables:
The Code is as follows:
Function classDialog ()
{
Var box = "sdfsdf"; // init, insert, and other functions call public variables very conveniently, and call internal functions very conveniently (such as directly calling search ()).
This. init = function (){....};
This. insert = function (){....};
This. pop = function (){....};
Function search (){....}
}
Var Dialog = new classDialog ();
Dialog. init ();
TinyMCE defines another function in the init: function () {} function when you need to use a function like a function. However, in this case, this function can only be called by init, other methods cannot share this private function.
Of course, there is no example of a private function being called by multiple public functions yet.
I would like to ask you, since function () {} closure is so convenient to create objects, why is the {} method so widely used?
Is there any defect in the object created by function?
Reply:
For directly using {} to create an object .. this scenario is used when a very small number of objects are created without encapsulation, it is very convenient to use constructor to instantiate objects when objects need to be created in batches. Let's take a look at the specific situation.
These two are completely different.
{} Can be considered as a singleton (Singleton Mode)
Function () {} returns an object. Every time a NEW object is returned, it is a different object!
The above also said {} is more efficient. And new is not required. {} Is globally fixed and can be expanded at will.
In general, {} is indeed highly efficient. It is easy to use, but it is better to use function in some ways.