www.webdeveloper.com
Results 1 to 10 of 10

Thread: [RESOLVED] Object Accessors ([SG]etters)

  1. #1
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792

    resolved [RESOLVED] Object Accessors ([SG]etters)

    Hi All,

    After searching for what feels like a lifetime, I am now seeking the opinions of anyone who has already tried this, or even better has got it working:

    Javascript allows the functionality of defining proper Object accessors using the Object.defineProperty method, or the __defineGetter__/__defineSetter__ functions. However IE8 only supports this using DOM elements.

    The code I have right now...

    Code:
    var myObj = {},
    
    if (Object.defineProperty) {
    	try {
    		Object.defineProperty(myObj, 'myProperty', {
    			get : function(){},
    			set : function(val){}
    		});
    	} catch(e) {
    		//IE8
    	}
    } else
    if (myObj.__defineGetter__) {
    	if (getter) {myObj.__defineGetter__('myProperty', function(){});}
    	if (setter) {myObj.__defineSetter__('myProperty', function(val){});}
    } else {
    		//IE6/7
    }
    Now this works great if I support Internet Explorer from version 9.

    My other option is to use "jQuery style" accessors, where you define a function wrapper to determine if the setter or getter function needs calling by specifying an argument:

    Code:
    function Property(obj, name, getter, setter)
    {
    	obj[name] = function()
    	{
    		return (arguments.length ? setter : getter).apply(obj, arguments);
    	};
    }
    This would obviously work in all browsers, but doesn't look as nice as the first when assigning or retrieving values.

    Before anyone asks... I do require accessors for argument evaluation, so I cannot just do straight forward assignments, and the defineProperty method of doing it would be first prize.

    Many thanks.
    JavaScript: Learn | Validate | Compact

  2. #2
    Join Date
    Jan 2011
    Posts
    117
    so what's wrong with working methods like


    Get:
    OBJECT.name
    OBJECT["name"]

    Set:
    OBJECT.name = value
    OBJECT["name"]=value

    Rem:
    delete OBJECT.name
    delete OBJECT["name"]

    don't they work cross-browserly for you?

  3. #3
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Quote Originally Posted by Troy III View Post
    so what's wrong with working methods like


    Get:
    OBJECT.name
    OBJECT["name"]

    Set:
    OBJECT.name = value
    OBJECT["name"]=value

    Rem:
    delete OBJECT.name
    delete OBJECT["name"]

    don't they work cross-browserly for you?
    Direct object assignments do work, but that's not what I'm asking. Property accessors work using functions to set or get the value, while enabling the developer to evaluate the value or run extra code.

    If you don't know what setters/getters are, here are some references:

    https://developer.mozilla.org/en/Cor...rs_and_setters
    http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx

    I think the way that I should be asking the question is: should I ignore the existence of < IE9 and use current standards to create my properties, or go for a more compatible (but uglier looking) "jquery style" approach?

    Thanks again.
    JavaScript: Learn | Validate | Compact

  4. #4
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Getters can seemingly be accomplished in a cross-browser manner like so:
    http://zaa.ch/post/918976466/a-naive...getter-pattern

    Not so sure about setters ...
    Jon Wire

    thepointless.com | rounded corner generator

    I agree with Apple. Flash is just terrible.

    Use CODE tags!

  5. #5
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by bionoid View Post
    I think the way that I should be asking the question is: should I ignore the existence of < IE9 and use current standards to create my properties, or go for a more compatible (but uglier looking) "jquery style" approach?
    why cripple an app that could last for years by supporting one browser that's already 2 versions (and 3-5 years) behind?

    If you were designing an awesome roller coaster, you'll probably end up with a height requirement that will leave some folks out, but roller coasters that EVERYONE can ride are almost always lame, slow, and boring.


    toString and valueOf provide getters for all user objects in all versions of js.
    you can make a timeout-based watcher for oldIE to invoke setters.

    basically, before you save or whatever, and if IE<9, iterate your object and fire the setter method for any changed (or just all) properties.


    I can't speak for your project's aims and criticality, so i don't know what the setters are for. Most importantly it matters if a delay in firing set() in IE7/8 is a deal-breaker, minor inconvenience, or something to pretend doesn't exist.
    Last edited by rnd me; 04-04-2012 at 12:01 PM.

  6. #6
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    As nice and neat as I think "true" getters and setters are, I think "Java-style" getters and setters (explicit getVar() and setVar() methods) are in some way better anyway. It makes it clear which updates may trigger other actions -- which variable sets and gets are "heavy" operations versus "light" ones.
    Jon Wire

    thepointless.com | rounded corner generator

    I agree with Apple. Flash is just terrible.

    Use CODE tags!

  7. #7
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Thanks guys.

    After some serious consideration I have decided that I want the "awesome roller coaster". So basically only ES5 capable browsers will be able to interpret the code (I know this leaves a huge amount of internet users out, but I'm no longer concerned).

    All your help was truly appreciated.
    JavaScript: Learn | Validate | Compact

  8. #8
    Join Date
    Jan 2007
    Location
    Wisconsin
    Posts
    2,120
    Another really nutty option, if you're in an extremely geeky mood, is to write subscripting language or script preprocessor. You could embed it in script tags, but set the type='text/javascript-plus' or something. Then, your final script tag just needs to be a preprocessor of some sort.

    You could even take the opportunity to write in fancy things like operator overloading.
    Jon Wire

    thepointless.com | rounded corner generator

    I agree with Apple. Flash is just terrible.

    Use CODE tags!

  9. #9
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    If you're thinking of me writing a script parser, I know I'm completely unqualified for the job. Personally, I feel Javascript is the most flexible language I've come across so far, and I can do pretty much everything I can think of already… even more so with the later browsers (and mobile devices).

    As my pet project is more of an experiment, I don't see why I should worry about the average person who doesn't know how to install a better browser. By the time I finish this thing all the compatibility problems I'm currently worried about should have disappeared anyway (hopefully).

    JavaScript: Learn | Validate | Compact

  10. #10
    Join Date
    Jan 2011
    Posts
    117
    Quote Originally Posted by bionoid View Post
    I think the way that I should be asking the question is:

    1. should I ignore the existence of < IE9 and use current standards to create my properties, or

    2. go for a more compatible (but uglier looking) "jquery style" approach?

    Thanks again.
    1. That's your call.
    2. Your call again!

    These features are ES5.
    And only Gen 5 browsers will recognize them. You can't ask a tape recorder to burn your CDs.

    So you either use Tape or CD, of course the tape quality is unsurpassed, but it wears with time. But standard CDs are limited to 44.1kHz specter. You can do faster skips etc. Theoretically never lose that 44.1 quality, but as we all know the CD surface itself can go trashy in less than 2-3 years.


    Code:
    Object properties in classic setup can have functions to...:
    Object.computableProp = function(arg){return [arg.compute]}
    Suppose you'd like to add a current time and date value to your Object that returns anacurate and actual value whenever you call for it:

    Code:
    OBJECT.currentDate = function(){return new Date().toLocaleDateString()}
    OBJECT.currentTime = function(){return new Date().toLocaleTimeString()}
    
    OBJECT.currentDate();
    >> "Weekday, Month Day, Year"
    OBJECT.currentTime();
    >> "hh:mm:ss"
    "Modern way" can add some native-like support to its call but it's basically the same.

    Code:
    OBJECT= {
        get currentDate(){return new Date().toLocaleDateString()},
        get currentTime(){return new Date().toLocaleTimeString()} 
        };
    
    OBJECT.currentDate;
    >> "Weekday, Month Day, Year"
    OBJECT.currentTime;
    >> "hh:mm:ss"
    The only problem is that you can't add dontEnum instruction to the classic one. But far more complicated functions and procedures can be used to add a property value method to your classical objects. And function arguments can be used to modify the processing instructions. But in the end it all falls back to the coders skills and creativity.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles