MickMalone1983
MickMalone1983

Reputation: 1054

Writing jQuery-style function chains in AS3 and other class-based languages

This isn't a specific problem I have, more a choice I could make, but I do believe the question is relevant for SO as there may be a 'proper' OO answer, as well as a performance benefit/loss to doing this. I'm working in AS3, but I believe the question would be relevant for other class-based/oo languages.

I was trying to figure a way to have Java-style multiple constructors for a class with different parameters (which is another story) but this got me thinking about jQuery, and how it chains functions by having them, where possible, return the object they are being called upon.

It doesn't always make for the neatest code with jQuery, and I guess it's a different practice to the classical approach, but I wondered if there is anything to be said for this method:

//execute chains of methods on creation, as each returns its parent class (person)
var person:Person = new Person().male('a male', 25).wakeUp().lookAround();

//Or later
person.getUp().rubEyes();

...and whether having member functions all returning an object which will often not be needed represent any significant waste/a performance issue?

It seems like a good way to save code and also represent sequences of functions in a more readable way, I wondered if anyone could help.

Thanks in advance

Upvotes: 3

Views: 230

Answers (1)

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

Yes, there is something to be said for person.getUp().rubEyes(): semantically it looks better. That's all.

new Person().male('a male', 25) is an entirely different case though. Male is not a verb like getUp. I would prefer: new Person({ gender: 'male', age: 25}).

Is there a significant performance hit when the returned object is not used? No. First of all, most (jit) compilers are smart enough to figure out that the object returned is never used and will therefore not execute those instructions at all. This is an optimization strategy called dead code elimination. Secondly, even if the compiler would not perform this optimization then still we are talking about a few measly clockcycles. Nothing you should worry about. In general I would advise you not to worry about these kind of performance issues at all. Better focus your optimization efforts on the parts of your code the compiler can not help you with (i.e. design, algorithms, etc).

Have fun chaining!

Upvotes: 2

Related Questions