0

I'm working on a dynamic validation system. For some reason, shift() on the args array mainfunc passes to validateNumber does not act properly. Here's the code with output in comments next to alert boxes:

function mainfunc (func){
    //this calls the function validateNumber and passes args to it.
    this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

function validateNumber(args) {
    alert(args); //this functions normally. for example, displays fish,3,5
    var text = args.shift; //would expect this to return 'fish', right?
    alert(text); //instead of 'fish' alerts 'function shift() { [native code] }'. This is the problem.
    var minimum = args.shift;
    var maximum = args.shift;
    return text;
}

validationArgs = classList[i].split('-');
    functionName = validationArgs.shift();
    validationArgs.unshift($(this).val());
    mainfunc(functionName, validationArgs); //calls mainfunc which calls the function

I'm stumped as to why this behaves this way. Note: I cribbed mainfunc from this StackOverflow answer: Calling dynamic function with dynamic parameters in Javascript

Edit: Oh, my goodness. I am an idiot. I even use shift() correctly in the title of the question! Thanks all.

Community
  • 1
  • 1
Michael
  • 774
  • 7
  • 26

4 Answers4

2

This:

var text = args.shift;

is not a method call, you want:

var text = args.shift();

All your original does is assigns the shift method from args to text, hence your:

function shift() { [native code] }

output in your alert. Doing a args.shift won't have any effect on args so these two:

var minimum = args.shift;
var maximum = args.shift;

just give you two more reference's to args.shift without changing args at all.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
2
var text = args.shift; //would expect this to return 'fish', right?

Wrong. You need the parens to call a function. Otherwise you will just get the function itself (which you saw in the alert message).

var text = args.shift();
Thilo
  • 257,207
  • 101
  • 511
  • 656
1
var text = args.shift; //would expect this to return 'fish', right?

shift is a method, did you mean to call it or assign a reference?

RobG
  • 142,382
  • 31
  • 172
  • 209
0

Just to complete the explanation here of what was going on:

var p = args.shift;

is a method assignment. You've assigned the function shift found on the object args to the variable p, but not actually executed that function. At this point, p contains a reference to the function shift. Thus, when you alert(p), you see a native code reference (that's the code behind the shift function).

Whereas:

var p = args.shift();

finds the function named shift on the args object and executes it without any parameters and then assigns the return value of that method to the variable p.

jfriend00
  • 683,504
  • 96
  • 985
  • 979