On Sat, Mar 5, 2011 at 11:04 PM, Tom de Koning <[email protected]>wrote:
>
> Hi all,
>
> I have been working with JS for quite a while, but coming from a .Net
> background. I was wondering if it is possible to do something like
> this in JavaScript:
>
> var expected = 5;
>
> var result = sut.somemethod(param1);
> result.shouldEqual(expected);
>
> Now, the key thing is that I'd like to have an extension on any object
> be it string, Integer or regular object to internally call one of the
> QUnit methods (in this case equal(result, expected);
>
> I have been playing with something like: Object.prototype.shouldEqual
> = function(expected){
> equal(this, expected);
> }
>
> But this (obviously) does not work. Is there a way to get this kind of
> syntax sugar?
>
That's actually exactly how it works. Maybe the missing link is how you
call/define `equal`?
If you define a new method on Object's prototype the new method will be
callable from any object (and primitives like strings and numbers are
coerced to their object container first if you try to access a property of
them). So basically, your shouldEqual method should be properly callable
from just about anywhere, unless you've done something shady yourself (you
can obviously prevent it).
So how have you defined equal? Try to look at that. Maybe it's part of a
"namespace"? In the case of js that would be just another object, maybe
something like `QUnit.equal`? I don't know QUnit. Or maybe the method is
actually called `equals`? With a trailing s.
Good luck.
- peter
--
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]