Prototype not working:

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • James Pittman

    Prototype not working:

    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(functio n, argsExpected, argsPassed, defaults);

    But not if I define it like this:

    Function.protot ype.getArgs(arg sExpected, argsPassed, defaults);

    I get a javascript error saying "this.getAr gs 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.protot ype.getArgs = function(argsEx pected, 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[i] 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('seda n', 4);
    var coup = new BodyStyle('coup ', 2);
    var wagon = new BodyStyle('wago n', 5);

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

    Any suggestions?
    Thanks,
    Jamie



  • Douglas Crockford

    #2
    Re: Prototype not working:

    > I have the method created, and it works if I define it like this:[color=blue]
    >
    > function getArgs(functio n, argsExpected, argsPassed, defaults);
    >
    > But not if I define it like this:
    >
    > Function.protot ype.getArgs(arg sExpected, argsPassed, defaults);[/color]
    [color=blue]
    > function BodyStyle() {
    > this.getArgs(['style', 'doors'], arguments, ['coup', 2]);
    > }
    >[/color]


    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.

    Comment

    Working...