4

When working with JavaScript I've come across a situation where I'm not sure if what I'm trying to accomplish is possible:

Considering the following object:

var data = {};

Is it possible to modify "data" in a way that when extending it in the following way

data.entry_1 = {
    'prop_1': 'set_1',
    'prop_2': 'set_2'
};

a new property gets automatically attached to the new object, that is to say

data.entry_1 = {
    'prop_1': 'set_1',
    'prop_2': 'set_2',
    id: 1 // automatically created property
};

Is it possible to accomplish the above without having to use "external" methods, e.g. no data.newEntry(object)?

2
  • Look into javascript prototypes. Commented Jun 13, 2012 at 8:41
  • 1
    Currently there's no possible way to do so but wait for some time and try again when Firefox rolls out Proxy objects. If you are too impatient you may even get your hands on node-proxy. Cheers. =) Commented Jun 13, 2012 at 8:58

1 Answer 1

1
var data = {
   set entry_1 (val) {
       for(var i in val) { this[i] = val[i] };
       this["id"] = 1;
   }
}

Supported in IE9+ and all other modern browsers.

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

1 Comment

Thanks for all the quick replies! I won't be using prototypes as messing around with Object.prototype is not really what I want... As far as setters are concerned: That's closest to what I'm looking for. If a general setter, that is to say not only for enty_1, but for any entry x could be specified my problem would be resolved. And that is what proxies are getting at, at least from what I've read on Mozilla. Guess I'll be sticking to good ol' objects methods for now. Again, thanks for all the answers!

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.