How to write better (or more elegantly) javascript without framework in order to prevent global variable pollution, etc.

< H2 > in the form of a function < / H2 >
// 
let cook = function(){
    let FoodMaterial = "Tomatoes"; //:
    let Spice = ""; //:
    return {
        buy:function(){
            console.log("" + FoodMaterial + "" + "Spice" );
        },
        doFood:function(){
            console.log(`${FoodMaterial}`);
        },
        setFood:function(food){
            //
            food && (FoodMaterial = food);
        }
    }
}
let o = cook();
o.setFood("");
o.buy();    //Spice
o.doFood();//     

< H2 > the form of the object < / H2 >
let cook = {
        FoodMaterial : "Tomatoes", //:
        Spice :"", //:
           buy:function(){
              console.log("" + FoodMaterial + "" + "Spice" );
        },
        doFood:function(){
              console.log(`${FoodMaterial}`);
        },
        setFood:function(food){
                //
           food && (FoodMaterial = food);
        }
    }
    let o = cook;
    o.setFood("");
    o.buy();    //Spice
    o.doFood();//

question 1:

question 2:

js,
May.23,2021

answer question one, the two uses are different.
object form:

let o1 = cook; let o2 = cook; 

o1 and o2 point to the same memory address, so o1 , o2 , and cook can be considered to be the same object.

The form of

function:

let o1 = cook(); let o2 = cook(); 

every time a function is executed, return an object, and two objects are created when the function is executed twice, so o1 and o2 are not associated.


A closed space solves all variable pollution , function repeats phenomenon

es6 lef/const

or

(function(){
    //cose
    var a=1;
    console.log(a);//1
})();
(function(){
    //cose
    var a=2;
    console.log(a);//2
})();
console.log(a);//not defined

to make an analogy, is it better to create an instance with a class or to write an instance directly?
I don't know what to compare, but the answer is to use both and look at the requirements.


if it is a singleton, the latter is obviously better; if it is a normal class, then you should use new . Nothing else is different.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1eb4713-24da.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1eb4713-24da.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?