简体   繁体   中英

What kind of object am I creating here?

I see many sites trying to prevent scope pollution by creating and populating a single object. For example:

var $ = {}
$.something = function() {
   ...
};

But I am wondering about the follow initialisation:

var $ = function() {
    // Something
}
$.something_two = function...

Is there any difference between the two and does the second code initialise a class instance upon each call?

In JavaScript all values, except primitives, are objects.

Ran my own version of your code to help demonstrate:

在此处输入图片说明

Also note the types of the objects created. In your first example $ is an object which contains the function(s). In the second, $ is a function (object) with a property which is also a function:

在此处输入图片说明

Either option would be ideal for preventing scope pollution, the first example is the most consistent with object creation standards.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM