get and set on properties

Posted on
  • Hi Gordon

    I just found learned the functionality of get and set.

    http://jsconsole.com/?var%20person%20%3D­%20%7B%0A%20%20_name%3A%20%27Marion%27%2­C%0A%20%20get%20name()%20%7B%0A%20%20%20­console.log(%27read%5Cn%27)%3B%0A%20%20%­20return%20this._name%3B%0A%20%20%7D%2C%­0A%20%20set%20name(value)%20%7B%0A%20%20­%20%20console.log(%27write%5Cn%27)%3B%0A­%20%20%20%20this._name%3Dvalue%3B%0A%20%­20%7D%0A%7D%3B%0A%0Aperson.name%3D%27Mic­helle%27%3B

    Code:

    var person = {
    _name: 'Marion',
    get name() {
    console.log('read\n');
    return this._name;
    },
    set name(value) {

    console.log('write\n');
    this._name=value;
    

    }
    };

    person.name='Michelle';

    I just got a syntax error. Any chance that this will work on espruino too ?

    Thanks

    Sacha

  • Gordon mentioned in the kickstarter comments (IIRC - it was somewhere) that getters and setters were one of the more exotic parts of javascript that are not implemented on Espruino.

    Here it is:

    Creator Gordon Williams on November 6
    @Milan Espruino supports just over half of what's in that table. I've tried to get the base language pretty good, so if you write sensible ES5 code then it'll work, but some of the more strange features (reserved words as property names, getters+setters, etc) aren't implemented yet. One big feature that's not in there is regular expressions, but hopefully that will come at some point in the future.
    If someone comes to me with existing code that could run but doesn't then I'll do what I can do make it work though.
    It's all open source and you can compile Espruino for Linux or Mac pretty easily, so you can try it out right now if you want to :)

  • Many thanks DrAzzy

    It would be a nice feature in the espruino enviroment. With getters and setters nice objectoriented implementations could be made like:

    mycar.light='on'; // Hidden catch function implements the functionality

    If(mycar.ambientsensor<=5) { mycar.light='on'; } // Provided by the hidden getter function, done as above.

    Best regards

    Sacha

  • Hi Sacha,

    Thanks - I'm afraid it is quite far down my priority list at the moment though - as it doesn't actually allow you to do anything that you can't do already just by writing .setLight('on').

  • Hi Gordon

    No Problem. I just red a javascript book and discovered setters and getters the first time.
    Had some ideas to use them on espruino too.

    Best regards

    Sacha

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

get and set on properties

Posted by Avatar for Sacha @Sacha

Actions