开发者

Is there an object type that returns both false in an if block and can have properties added to it and retrieved from it?

I'开发者_如何学Cm trying to write a failsafe into the prototype library for it's "$()" selection function.

So far I've gotten to where I've overwritten the "$" global with a function of my own that in the case of $() returning null, it will actually log the error into the database and return a "dummy" element that gets extended by prototype so you can run your action on that.

This is to prevent failures of the entire system caused by trying to run an element method on the "null" object.

The problem with my solution is that as sneaky and useful as it might be, it returns the dummy div and therefore returns true in an if () statement. Is there any way I can have it return a "falsy" value that can also be extended by prototype? I'm open to any other clever approaches as well.


As you probably already know, Javascript converts to boolean using the following rules:

Undefined => false
Null => false
Boolean => Value of value
Number => Value of false if number is 0 or NaN; otherwise, true
String => Value of false if string is empty; otherwise, true
Object => true

Since in general any Object evaluates to true, it seems to me the only way to achieve what you're asking is to extend String.prototype with bogus implementations of prototype.js Element functions, and then return the empty string from your custom "$" function. Here's the general idea:

<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script>
Object.extend(String.prototype, {
 foo : function() { document.write('<br/>foo called') }
});

o = ""
if (o) { document.write('true') } else { document.write('false') }
o.foo()
</script>

When run, this shows:

false
foo called

It's a bit kludgy though, cause you'd be adding these functions to all strings, not just the empty string. Also, I'm not sure overall that you're really better off "masking" the element-not-found issues with this special object. A fail-fast approach is often the better approach as it avoids subtle errors which are several steps removed from the root cause.


Altering the expected outcome of $() is too dangerous. If you want to avoid breaking existing scripts either make sure you always check for nulls (preferred)...

if ($('element')) $('element').hide();

...or use the result in a way that is more tolerant to missing elements...

$$('#element').invoke('hide');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜