Josh
Josh

Reputation: 8477

JavaScript embedded function within function

I came across this example on the MDN and it doesn't work as described:

function makePerson(first, last) {
    return {
        first: first,
        last: last,
        fullName: function() {
            return this.first + ' ' + this.last;
        },
        fullNameReversed: function() {
            return this.last + ', ' + this.first;
        }
    }
}

Example Call:
> s = makePerson("Simon", "Willison")
> s.fullName()
Simon Willison
> s.fullNameReversed()
Willison, Simon

The article was written in 2006, and in both IE10 and Chrome 26, it just displays the literal code for the fullName and fullNameReversed functions. Is this functionality no longer working for modern browsers?

Upvotes: 0

Views: 71

Answers (3)

Nick
Nick

Reputation: 146

It sounds like you've missed out the parentheses from the end of your function call.

Try

s.fullName();

instead of

s.fullName;

Upvotes: 1

Pooyan Arab
Pooyan Arab

Reputation: 136

If you receive the code for the function, it is probably because you call the function like s.fullName and not s.fullName() (You are missing the parenthesis)

Upvotes: 1

Xotic750
Xotic750

Reputation: 23482

Appears to work just fine on chromium v25

Javascript

function makePerson(first, last) {
    return {
        first: first,
        last: last,
        fullName: function() {
            return this.first + ' ' + this.last;
        },
        fullNameReversed: function() {
            return this.last + ', ' + this.first;
        }
    }
}

var s = makePerson("Simon", "Willison");
console.log(s.fullName());
console.log(s.fullNameReversed());

Output

Simon Willison
Willison, Simon 

On jsfiddle

Upvotes: 1

Related Questions