Home  >  Article  >  Web Front-end  >  Is it better to use {} or function(){} in js object-oriented design (constructor)_js object-oriented design

Is it better to use {} or function(){} in js object-oriented design (constructor)_js object-oriented design

WBOY
WBOYOriginal
2016-05-16 18:00:27782browse

I have seen many JavaScript projects on the Internet, and the objects used are all in the form of {}:
For example, jQuery, TinyMCE, etc. are all in the form:

Copy code 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, variables):
Copy code The code is as follows:

function classDialog()
{
var box = "sdfsdf"; //It will be very complicated to call public variables in init, insert and other functions Convenient, it is also very convenient to call internal functions (for example, you can call search() directly).

this.init = function() { .... };
this.insert = function() { . ... };
this.pop = function() { .... };

function search() { .... }
}
var Dialog = new classDialog ();
Dialog.init();

See that when TinyMCE needs to use a function, it defines a function inside init: function() { } , but in this case, this function can only be called by init, and other methods cannot share this private function.
Of course, I have not yet seen an example of a private function being called by multiple public functions.


I would like to ask you all, since the function(){} closure is so convenient to use to create objects, why is the {} method so widely used?

Is it function() {}? What are the defects of the created objects?

Reply:
For directly using {} to create objects. In this case, very few objects are created and no encapsulation is required. It is very convenient to use the constructor to instantiate objects when you need to create objects in batches. It mainly depends on the specific situation

The two are completely different things.

{} can be regarded as a singleton (singleton mode)

function(){} returns an object. Each time NEW is returned, a different object is returned!

Some students above also said {} is more efficient. And no need to use new. {} is globally fixed and can be arbitrarily expanded.

Generally speaking, {} is really efficient and easy to use, but it is better to use function when you don’t want to expose certain methods.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn