Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6723659
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T09:35:43+00:00 2026-05-26T09:35:43+00:00

I am aware of how to create getters and setters for properties whose names

  • 0

I am aware of how to create getters and setters for properties whose names one already knows, by doing something like this:

// A trivial example:
function MyObject(val){
    this.count = 0;
    this.value = val;
}
MyObject.prototype = {
    get value(){
        return this.count < 2 ? "Go away" : this._value;
    },
    set value(val){
        this._value = val + (++this.count);
    }
};
var a = new MyObject('foo');

alert(a.value); // --> "Go away"
a.value = 'bar';
alert(a.value); // --> "bar2"

Now, my question is, is it possible to define sort of catch-all getters and setters like these? I.e., create getters and setters for any property name which isn’t already defined.

The concept is possible in PHP using the __get() and __set() magic methods (see the PHP documentation for information on these), so I’m really asking is there a JavaScript equivalent to these?

Needless to say, I’d ideally like a solution that is cross-browser compatible.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T09:35:44+00:00Added an answer on May 26, 2026 at 9:35 am

    This changed as of the ES2015 (aka "ES6") specification: JavaScript now has proxies. Proxies let you create objects that are true proxies for (facades on) other objects. Here’s a simple example that turns any property values that are strings to all caps on retrieval, and returns "missing" instead of undefined for a property that doesn’t exist:

    "use strict";
    if (typeof Proxy == "undefined") {
        throw new Error("This browser doesn't support Proxy");
    }
    let original = {
        example: "value",
    };
    let proxy = new Proxy(original, {
        get(target, name, receiver) {
            if (Reflect.has(target, name)) {
                let rv = Reflect.get(target, name, receiver);
                if (typeof rv === "string") {
                    rv = rv.toUpperCase();
                }
                return rv;
            }
            return "missing";
          }
    });
    console.log(`original.example = ${original.example}`); // "original.example = value"
    console.log(`proxy.example = ${proxy.example}`);       // "proxy.example = VALUE"
    console.log(`proxy.unknown = ${proxy.unknown}`);       // "proxy.unknown = missing"
    original.example = "updated";
    console.log(`original.example = ${original.example}`); // "original.example = updated"
    console.log(`proxy.example = ${proxy.example}`);       // "proxy.example = UPDATED"

    Operations you don’t override have their default behavior. In the above, all we override is get, but there’s a whole list of operations you can hook into.

    In the get handler function’s arguments list:

    • target is the object being proxied (original, in our case).
    • name is (of course) the name of the property being retrieved, which is usually a string but could also be a Symbol.
    • receiver is the object that should be used as this in the getter function if the property is an accessor rather than a data property. In the normal case this is the proxy or something that inherits from it, but it can be anything since the trap may be triggered by Reflect.get.

    This lets you create an object with the catch-all getter and setter feature you want:

    "use strict";
    if (typeof Proxy == "undefined") {
        throw new Error("This browser doesn't support Proxy");
    }
    let obj = new Proxy({}, {
        get(target, name, receiver) {
            if (!Reflect.has(target, name)) {
                console.log("Getting non-existent property '" + name + "'");
                return undefined;
            }
            return Reflect.get(target, name, receiver);
        },
        set(target, name, value, receiver) {
            if (!Reflect.has(target, name)) {
                console.log(`Setting non-existent property '${name}', initial value: ${value}`);
            }
            return Reflect.set(target, name, value, receiver);
        }
    });
    
    console.log(`[before] obj.example = ${obj.example}`);
    obj.example = "value";
    console.log(`[after] obj.example = ${obj.example}`);

    The output of the above is:

    Getting non-existent property 'example'
    [before] obj.example = undefined
    Setting non-existent property 'example', initial value: value
    [after] obj.example = value

    Note how we get the "non-existent" message when we try to retrieve example when it doesn’t yet exist, and again when we create it, but not after that.


    Answer from 2011 (obsoleted by the above, still relevant to environments limited to ES5 features like Internet Explorer):

    No, JavaScript doesn’t have a catch-all property feature. The accessor syntax you’re using is covered in Section 11.1.5 of the spec, and doesn’t offer any wildcard or something like that.

    You could, of course, implement a function to do it, but I’m guessing you probably don’t want to use f = obj.prop("example"); rather than f = obj.example; and obj.prop("example", value); rather than obj.example = value; (which would be necessary for the function to handle unknown properties).

    FWIW, the getter function (I didn’t bother with setter logic) would look something like this:

    MyObject.prototype.prop = function(propName) {
        if (propName in this) {
            // This object or its prototype already has this property,
            // return the existing value.
            return this[propName];
        }
    
        // ...Catch-all, deal with undefined property here...
    };
    

    But again, I can’t imagine you’d really want to do that, because of how it changes how you use the object.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I already aware of this:- Typeface typefaceArial= Typeface.createFromAsset(context.getAssets(), arial.ttf); but when I create the
I am aware that one can create template filters in Django templates such as
I wanted to create an IDN-aware formencode validator to use in one of my
I am aware that using setters in dealloc can create problems, if any other
I would like to create a Spring's bean producer method which is aware who
I have to create a select box like this. I have been able to
I would like to use CSS to create nice round border. I'm aware of
I'd like to create some helper methods that are inheritance aware. I'd like them
I'm trying to write an Eclipse template which will create getters and setters when
I would like to create a image uploading service (yes, i am aware of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.