By the way, CoffeeScript provides a convenient sugar for that:
obj.foo?.bar? and stuff?()
which desugars into (notice, how elegantly the last "stuff" is checked
to be a functon):
var _ref;
(((_ref = obj.foo) != null ? _ref.bar : void 0) != null) && (typeof
stuff == "function" ? stuff() : void 0);
It's possible also to assign (so the way PHP uses is even more
convenient; OTOH, sometimes it's better to show an error without
creating intermediate properties in path, and in this case PHP fails).
Coffee:
((obj ?= {}) # if no obj, set it to {}
.foo ?={}) # if no obj.foo, set it to {}
.bar ?= 10 # if no obj.foo.bar, set it to 10
alert(obj.foo.bar) # 10
Unfortunately in current JS we should do this in desugared way.
Dmitry.
On 16.02.2011 15:51, Andrew Dodson wrote:
Your dreaming!
On 16 Feb 2011 12:09, "Jason Persampieri" <[email protected]
<mailto:[email protected]>> wrote:
(It's 4am for me, I'm sick, and meds have been taken... so this may
be incredibly dumb)
An earlier thread got me thinking. Currently when checking a value
nested several layers deep within an object, you have to do something
along the lines of:
d = {};
[stuff]
if ( d && d.foo && d.foo.bar && d.foo.bar.bam ) {
[stuff]
}
And setting it is even more verbose:
d = {};
d.foo = d.foo || {};
... you get the point.
What would happen if "undefined" were smarter, kinda like an empty
ref in Perl (did I really just say that? ugh.). Why can't we do:
d = {};
[stuff]
if ( d.foo.bar.bam ) {
[stuff]
}
and
d = {};
d.foo.bar.bam = "Hi Mentors!"; // { foo: { bar: { bam: "Hi Mentors!"
} } }
What's the harm in having the compiler do that bit of optimization
for us? What code would it break? Is there any code that it would
make less maintainable? Do custom getters/setters break this?
_jason
--
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]