3

I'm coming back to "raw" Javascript, and I'm writing classes like this:

var Person;

Person = (function() {

    function Person() {}

    Person.prototype.run = function() {};

    Person.prototype.jump = function() {};

    Person.prototype.talk = function() {};

    return Person;

})();

I feel like the repetition of Person.prototype isn't very DRY: it's also harder to avoid line wrapping. Are there common ways of addressing this? For example, one could assign Person.prototype to a small variable like cls, which would make the lines look more like

cls.run = function() {};

...but that might be too unconventional.

2 Answers 2

4

Since you do not have anything in the prototype you can simply assign a new object to it:

Person.prototype = {
    run: function() {},
    jump: function() {},
    walk: function() {}
};

Otherwise you could use a function such as jQuery's $.extend() to merge two objects:

$.extend(Person.prototype, {
    run: function() {},
    jump: function() {},
    walk: function() {}
});
Sign up to request clarification or add additional context in comments.

1 Comment

ah i completely forgot about that...+1.
2

That's not what DRY really means. Dang it, I have to write 'if' and 'function' a lot too. And I really cant stand 'return' and 'for'. ;)

DRY is for when functionality is copied and pasted, resulting in bloated code and a high maintenance cost. In this case, you are complaining more about the language syntax.

BTW, you are probably ahead of (i.e. more DRY) many people by defining methods on objects.

Having said all that, coffeescript allows you to be less verbose. Way less verbose. Many times you don't need parenthesis or braces, and you don't need prototype at all.

1 Comment

Well, repeating Person is kind of ugly - you'd have to change quite a few places in a large object if you ever decided to rename it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.