0

A small question for versed javascript programmers: There are two ways to declare a function in javascript.

A: javascript-object-notation

function MyLittleHouseA(name) {
    this.age = 88,
    this.name = name,
    this.getName = function()
    {
        return this.name;
    }
}

B: uhm, normal:

function MyLittleHouseB(name) {
    this.age = 88;
    this.name = name;
    //do some more proceduaral stuff upon 'construction'
    this.age = this.age + 20; 
    this.getName = function()
    {
        return this.name;
    }
}

I find A more elegant (and have a number of objects I want to turn into configurable options...), but might want to do some more stuff upon instance creation, hence I do need as shown in B.

Can these be mixed?

¡ Thanx !

1
  • 1
    Please don't delete questions like this. Either fully delete it (there should be a delete button beneath your question), or leave it up, even though you don't need the answer any more. People have already answered the question, and this information is left up for others to see, but now the answers doesn't make sense since the question text has changed. So decide if you want to leave it, or fully delete it. Commented Sep 10, 2010 at 11:06

1 Answer 1

3

Your first option doesn't use object notation. If you want to use object notation, you could write something like this:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        getName: function() {
            return name;
        }
    }
}

This has the advantage of not using this, which means you avoid any issues with the binding of this. It also hides age and name, which may or may not be desirable -- as it stands, there's no way for age to be accessed, while name is immutable since it can only be read via getName. If you want to expose age as a normal field:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        age: age,
        getName: function() {
            return name;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Michael, great answer! Far better then my very buggy question! Indeed I am dealing with all those "this" troubles. This will help me big time... Plus I like the "config object" colon-Style...

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.