/    Sign up×
Community /Pin to ProfileBookmark

[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 [B]Object.defineProperty[/B] method, or the [B]__defineGetter__/__defineSetter__[/B] 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
}[/CODE]

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);
};
}[/CODE]

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.

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@Troy_IIIApr 02.2012 — 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?
Copy linkTweet thisAlerts:
@bionoidauthorApr 02.2012 — 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?[/QUOTE]


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/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_getters_and_setters

http://msdn.microsoft.com/en-us/library/dd548687(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.
Copy linkTweet thisAlerts:
@svidgenApr 04.2012 — Getters can seemingly be accomplished in a cross-browser manner like so:

http://zaa.ch/post/918976466/a-naive-jscript-compatible-getter-pattern

Not so sure about setters ...
Copy linkTweet thisAlerts:
@rnd_meApr 04.2012 — 
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?
[/QUOTE]


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.
Copy linkTweet thisAlerts:
@svidgenApr 04.2012 — As nice and neat as I think "true" getters and setters are, I think "Java-style" getters and setters (explicit get[I]Var[/I]() and set[I]Var[/I]() 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.
Copy linkTweet thisAlerts:
@bionoidauthorApr 07.2012 — 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.
Copy linkTweet thisAlerts:
@svidgenApr 07.2012 — 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.
Copy linkTweet thisAlerts:
@bionoidauthorApr 07.2012 — 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&#8230; 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).

?
Copy linkTweet thisAlerts:
@Troy_IIIApr 08.2012 — 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.[/QUOTE]


  • 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]}[/CODE]


    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"[/CODE]


    "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"
    [/CODE]

    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.
    ×

    Success!

    Help @bionoid spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.25,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...