0

In an angular project, I have a user class with with several properties which should be updated whenever the model user.name is changed. Rather than make these regular anonymous functions, I thought I would make them self-executing anonymous functions so that I wouldn't have to execute them when I use these properties elsewhere.

Now however, when I try to pass parameters to the functions those parameters are undefined.

var messages = {
    'startingMessage' : 'You can enter your name here.',
    'nameOverflowMessage' : 'Oops, looks like that name is too long.',
    'invalidNameMessage' : 'I don\'t think that name will work',
    'validNameMessage' : 'This name looks good.'
}

//User Object
this.user = {
    'name' : 'Harry Jazz',
    'nameStatus' :  (function (name) {
        console.log(name)
        //check name is defined
        if(name === undefined) {
            return 'undefined';
        }
        //Check length
        if(name.length > 50) {
            return 'overflow';
        } 
        else {
            return 'valid';
        }
    }) (this),
    'message' : (function (nameStatus) {
        console.log(nameStatus);
        if (nameStatus === 'valid') {
            return messages.validNameMessage;
        }
        if (nameStatus === 'overflow') {
            return messages.nameOverflowMessage;
        }
        if (nameStatus === 'undefined') {
            return messages.invalidNameMessage;
        }
        return 'Huh? We don\'t have a message for this'
    }) (this.nameStatus)
}

Specifically, console.log reports that 'name' and 'nameStatus' are undefined. What am I doing wrong? I would appreciate any advice.

  • 1
    But the whole point is that they are functions whose logic is run later, isn't it?! – Bergi Jul 28 '16 at 23:07
  • See the duplicate for why `this` doesn't work in an object literal like you expect. – Bergi Jul 28 '16 at 23:08
  • In addition to the question Bergi used as the dupe target (I had to re-apply it; I call it 80%, but that's good enough here), note that you're also treating `this.nameStatus` as though it **called** the function attached to that property. It doesn't. It just refers to the function. To *call* it, you need `()` after it. – T.J. Crowder Jul 28 '16 at 23:12

0 Answers0