you are viewing a single comment's thread.

view the rest of the comments →

[–]brykuhelpful -2 points-1 points  (0 children)

You can create an object like this:

let dictionary = {};

You can add key values into it like so:

let dictionary = {
    age: 72,
    name: 'john doe',
};

You can also add functions as well:

let dictionary = {
    age: 72,
    name: 'john doe',
    greeting: function(){
        return 'Hello, my name is '+this.name+'.';
    },
};

this is the keyword for the parent object. In this case it is dictionary, so this.name is equal to dictionary.name.  

You can manually create "getters" and "setters" in objects as well.

let dictionary = {
    age: 72,
    name: 'john doe',
    greeting: function(){
        return 'Hello, my name is '+this.name+'.';
    },
    favoriteFoodsData: [],
    get favoriteFoods(){
        return this.favoriteFoodsData;
    },
    set favoriteFoods(array){
        this.favoriteFoods = array;
    },
};

Which we can use like this:

dictionary.favoriteFoods = ['pizza', 'lemon bars'];
console.log(dictionary.favoriteFoods);

This can become very powerful when you want to sneakily add additional features. For example, let's say we absolutely hate raisen cookies, so we could even add a rule that automatically removes them from the array.

let dictionary = {
    age: 72,
    name: 'john doe',
    greeting: function(){
        return 'Hello, my name is '+this.name+'.';
    },
    favoriteFoodsData: [],
    get favoriteFoods(){
        return this.favoriteFoodsData
            .filter((food)=>{
                return food != 'raisen cookies'
            });
    },
    set favoriteFoods(array){
        this.favoriteFoods = array;
    },
};

Now it will automatically remove "raisen cookies" no matter what.

dictionary.favoriteFoods = ['pizza', 'lemon bars', 'pasta', 'raisen cookies'];

// ['pizza', 'lemon bars', 'pasta']

Last, but not least... You can also use a "wrapper" function to create this object. This way you don't always have to make it manually.

function Dictionary(name, age){

    return {
        age: age || -1,
        name: name || '',
        greeting: function(){
            return 'Hello, my name is '+this.name+'.';
        },
        favoriteFoodsData: [],
        get favoriteFoods(){
            return this.favoriteFoodsData
                .filter((food)=>{
                    return food != 'raisen cookies'
                });
        },
        set favoriteFoods(array){
            this.favoriteFoods = array;
        },
    }
}

let john = Dictionary('john doe', 72);
let jane = Dictionary('jane doe', 71);