Arc Forumnew | comments | leaders | submitlogin
2 points by gnaritas 5980 days ago | link | parent

Wouldn't that be...

    function Person(first, last, age) {
        this.first = first;
        this.last = last;
        this.age = age;
        this.full = function() {
            return this.first + " " + this.last;
        };
        this.until = function(year) {
            return year - this.age;
        };
    }
There's really no reason return an anonymous literal object from the Person constructor unless I'm overlooking something, it has been a year or two since I played with JS much.


1 point by EliAndrewC 5980 days ago | link

You are correct; it's also been awhile since I played with Javascript, but I just checked "A Reintroduction to Javascript" then it listed both my way and your way as examples, describing your way as being cleaner: http://developer.mozilla.org/en/docs/A_re-introduction_to_Ja...

-----

2 points by tung 5976 days ago | link

I'd do it like this:

    function Person(first, last, age) {
        this.first = first;
        this.last = last;
        this.age = age;
    }
    
    Person.prototype.full = function () {
        return this.first + " " + this.last;
    };
    
    Person.prototype.until = function (year) {
        return year - this.age;
    };
You shouldn't really put functions inside the constructor function unless you really need the closure.

-----

1 point by gnaritas 5970 days ago | link

Which is handy if you want private instance variables. But you're right, prototype should be the first choice, like I said, it's been a while.

-----