0

I load a javascript file asynchronously and the file contains this line defined within a plugin defaults. It returns correct return value in some pages whereas in other pages the same file returns 'undefined' values. Any pointers?

login: '<p>Log in with your '+ fnc(code).name +' account</p>'

somewhere at the bottom of the same file I have defined the function:

 function fnc(s){
      if(s =='' || s == 'a'){
        this.name = 'name1';
        this.value = 'value1';
      }else if(s == 'b'){
        this.name = 'name2';
        this.value = 'value2';
      }else{
        this.name = 'name1';
        this.value = 'value1';
       }
      return this;
    }

For some reason, the function returns 'undefined'

UPDATE: "code" is a global variable that is present in some other file, depending on the value of that variable, I want to return different values from the function

UPDATE2: I want to return multiple values from the function, updated the code to reflect that.

neelmeg
  • 2,459
  • 6
  • 34
  • 46
  • 1
    How is this function being ran? `this` will be `window` unless you set its context. – gen_Eric Dec 28 '12 at 15:35
  • 1
    What is `code`? Your function only sets `name` in three specific cases, so it (may) stay at `undefined` otherwise. – pimvdb Dec 28 '12 at 15:36

3 Answers3

2

The value of this in that function is going to be either a reference to window or else undefined, depending on whether "strict mode" is in effect.

It really doesn't make a lot of sense for the function to be written like that. Seems like it should just be:

function fnc(s) {
  return s == '' || s == 'a' ? "name1" : s == "b" ? "name2" : null;
}

Then you'd just call it as fnc(code) with no need for a "name" property. As somebody else pointed out also, you don't make provisions for when the "code" is something other than the empty string, an "a", or a "b".

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

Are you passing a value to fnc other than '', 'a' or 'b', as it will return undefined

eleven11
  • 362
  • 2
  • 3
  • 12
2

this can refer to the document window, unless your writing an object, don't use this

function fnc(s){
    var rc = '';    
    if(s =='' || s == 'a'){
        rc = 'name1';
    } else if (s == 'b'){
        rc = 'name2';
    }
    return rc;
}
keeg
  • 3,990
  • 8
  • 49
  • 97
  • right but now you won't get undefined, now you'll get an empty value instead or whatever `var rc` is set to. Still bad practice to have `this` floating in a function at the bottom of the page somewhere. – keeg Dec 28 '12 at 15:41
  • 'this' was the problem, it got fixed now. – neelmeg Dec 28 '12 at 16:03