Prototype not working:

J

James Pittman

OK I have a script, designed to test my handling of named-parameters. That
is, I want to be able to call a Function as such:

function(val1, val2, val3); // order-based parameters
or
function({arg1: val1, arg2: val2, arg3: val3}); // named
parameters

and create a new method on the Function object to detect whether the user
used order-based or named paramters.

I have the method created, and it works if I define it like this:

function getArgs(function, argsExpected, argsPassed, defaults);

But not if I define it like this:

Function.prototype.getArgs(argsExpected, argsPassed, defaults);

I get a javascript error saying "this.getArgs is not a function".

I'd like to use "prototype" since that way it encapsulates "getArgs" in the
Function class.

Here is my code:

Function.prototype.getArgs = function(argsExpected, argsPassed,
arrDefaults) {
// some code to detect whether a function is passed named paramters
or order-based arguments
// argsExpected is an array of argument names
// argsPassed is always the "arguments" collection
// argsDefaults is an optional array of defaults for each arg in
argsExpected
// Sets this to the values passed in for each parameter i.
}

function BodyStyle() {
this.getArgs(['style', 'doors'], arguments, ['coup', 2]);
}

function Car() {
this.getArgs(['bodyStyle', 'make', 'model'], arguments, [undefined,
'Mazda', 'Miata']);
}

var sedan = new BodyStyle('sedan', 4);
var coup = new BodyStyle('coup', 2);
var wagon = new BodyStyle('wagon', 5);

var car1 = new Car(sedan, 'Toyota', 'Camry');

Any suggestions?
Thanks,
Jamie
 
D

Douglas Crockford

I have the method created, and it works if I define it like this:
function getArgs(function, argsExpected, argsPassed, defaults);

But not if I define it like this:

Function.prototype.getArgs(argsExpected, argsPassed, defaults);
function BodyStyle() {
this.getArgs(['style', 'doors'], arguments, ['coup', 2]);
}


The result is a method of functions. But you invoke it as a method of the
object, which of course is wrong. The method is not the object. Think of the
correspondence between object.method and this == object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,219
Latest member
Geraldine7

Latest Threads

Top