1

In my Javascript drag and drop build app, a variety of buildings can be built. The specific characteristics of these are all saved in one object, like

var buildings = {
house: ['#07DA21',12,12,0,20],
bank: ['#E7DFF2',16,16,0,3],
stadium: ['#000000',12,12,0,1],
townhall: ['#2082A8',20,8,0,1],
etcetera
}

So every building has a number of characteristics, like color, size, look which can be called as buildings[townhall][0] (referring to the color). The object changes as the user changes things. When clicking 'reset' however, the whole object should be reset to its initial settings again to start over, but I have no idea how to do that. For normal objects it is something like.

function building() {}
var building = new building();
delete building;
var building2 = new building();

You can easily delete and remake it, so the properties are reset. But my object is automatically initialized. Is there a way to turn my object into something that can be deleted and newly created, without making it very complicating, or a better way to store this information?

5
  • You can't delete properties declared in global scope, nor can you delete functions. See perfectionkills.com/understanding-delete/#property_attributes Commented Jun 6, 2010 at 17:44
  • That's an interesting read, but is there some way to set up my code differently then, so that it is not global, thus deletable, like the example of the objects declared with 'new'? Commented Jun 6, 2010 at 17:54
  • @Marcel, of course you can delete global variables (variables as you don't declare properties). Commented Jun 6, 2010 at 17:55
  • @Sean: Have you actually tried it? E.g.: var foo=1; console.log(delete foo); outputs false. Commented Jun 6, 2010 at 17:59
  • 1
    @Marcel, I was fooled by the fact that console uses eval which, behaves differently (as noted in the article). Commented Jun 6, 2010 at 18:04

2 Answers 2

3

You can keep initial state as a prototype on an object.

var Base = function(){};
    Base.prototype={a:1,b:2};
var c = new Base();

Now, you can change value of a or b to whatever you want. To restore, just use

delete c.a or delete c.b

You will get your initial value back. Hope this help.

Sign up to request clarification or add additional context in comments.

Comments

1

Just use a copy/clone method to restore the original state

var defaults = {
    foo: "bar"
};
var building;

function reset(){
    building = {};
    for (var key in defaults) {
        if (defaults.hasOwnProperty(key){
            building[key] = defaults[key];
        }
    }
}

Now you can just call reset() whenever you need to have building reset.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.