0

I'm pretty sure this is impossible but maybe someone clever out there knows if there is a chance of making this work. Is it possible to have code where:

1    myPerson = new Person();
2    myPerson.name = 'Charles Xavier';

Where the code on line #2 automatically checks if myPerson.setName exists and if so calls

myPerson.setName('Charles Xavier');

in place of of doing the direct assignment.

1
  • 1
    Create a helper function which does the check for you? Or why dont you do the check inside setName()? Commented Apr 17, 2014 at 15:12

2 Answers 2

2

Nope, sorry! It is possible in ES6, though:

var o = {};
Object.defineProperty(o, "name", {
  set: function (value) {
    console.log("Property 'name' set to: " + value);
    // store 'value' somewhere
  }
});

c.f. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

related: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Since this is not possible in < ES6, frameworks like AngularJS use dirty-checking (aka they check the value X times per second) to watch for property changes.

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

2 Comments

Dirty checking sounds terrible! Very cool that this type of functionality is coming with ES6 though.
@Kirk haha it does sound terrible but it works pretty well for AngularJS.
1

Not for all browser, but there's javascript proxy which is only work on firefox, and make this become useless. :D

var Validator = {
    set: function(obj, prop, value){
        if(prop == 'name' && setName in obj)
            obj.setName(value);

        obj[prop] = value;
    }
}

var myPerson = new Proxy(Person, Validator);
myPerson.name = 'Charles Xavier'; // This will call Validator.set

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.