Link to home
Start Free TrialLog in
Avatar of itnifl
itniflFlag for Norway

asked on

JavaScript example, whats wrong here?

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>

Open in new window


var customer = new function(name) {
    this.name = name;
    $('#one').html('Inside: ' + name);
    return {
        getName: function() {
            return name;
        },
        setName: function(newName) {
            name = newName;
        }
    };
}('Olaf');
customer.setName('Albert');
$('#two').html('Outside-1: ' + customer.getName());
$('#three').html('Outside-2: ' + customer.name)

Open in new window


Output:

Inside: Olaf
Outside-1: Albert
Outside-2: undefined

Why is the last output undefined? Didn't I set a property called name with a value?
Avatar of Jerry Miller
Jerry Miller
Flag of United States of America image

I would use a different identifier from 'name', there may be some conflict using multiple instances of name since it is a keyword. I think that you were setting this.name to itself and that was producing your undefined error.

var customer = new function(n) {
    this.name = n;
    $('#one').html('Inside: ' + n);
    return {
        getName: function() {
            return n;
        },
        setName: function(newName) {
            n = newName;
        }
    };
}('Olaf');
customer.setName('Albert');
$('#two').html('Outside-1: ' + customer.getName());
$('#three').html('Outside-2: ' + customer.name)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of itnifl

ASKER

If I do this customer.name also works:
var customer = new function(n) {
    this.name = n;
    $('#one').html('Inside: ' + n);
}('Olaf');

$('#three').html('Outside-2: ' + customer.name)

Open in new window


But if I choose to return what attributes are available like in the question, then this.name = n; will not set an attribute named name. Does it get overwritten by the return statement or what happens to it?