Вопрос

I am new to Javascript Object Literal, and I have problem understanding the mechanism behind this logic, and because of that, I don't know the right keyword to search either in Google, or SO.

Here's an example of my problem:

var dialog = {
    open: function(x){
        console.log(JSON.stringify(x))
    },
    type: {
        settings: {
            controller: '',
            click: false,
            clas: ''
        },
        foo: function(){
            this.settings.controller = 'Foo controller'
            this.settings.clas = 'Foo class'
            dialog.open(this.settings)
        },
        bar: function(){
            this.settings.click = true
            dialog.open(this.settings)
        }
     }
}

This is my issue:

//A
dialog.type.foo();
//B
dialog.type.bar();
//C
dialog.type.foo();

Why is it that when I run //C, dialog.type.settings is still retaining the value from foo? How can I default back to dialog.type.settings?

Это было полезно?

Решение

You only have one object to work with, so anything you changed in previous steps are "carried along" until you explicitly change them.

To work with a new dialog object each time I would recommend using a function that returns a new instance each time and hide the settings and open properties:

function dialog()
{
    var settings = {
        controller: '',
        click: false,
        clas: ''
    },
    open = function(x) {
        console.log(JSON.stringify(x));
    };

    return {
        type: {
            foo: function() {
                settings.controller = 'Foo controller';
                settings.clas = 'Foo class';
                open(settings);
            },
            bar: function() {
                settings.click = true;
                open(settings);
            }
        }
    };
}

And then:

var a = dialog();
a.type.foo();

var b = dialog();
b.type.bar();

var c = dialog();
c.type.foo();

Demo

It avoids the issues you would otherwise face with using this in all kinds of contexts, because settings and open are always within the scope of the API that you return from the dialog() function.

Другие советы

Your "foo" function is explicitly and deliberately changing the values of those "settings" properties. There's just one "settings" object, after all. If you want to revert the values, you'll have to write a function to do that.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top