2

Possible Duplicate:
Javascript syntax I haven't seen till now, what does it do really?

I was checking out a library called def.js which makes JavaScript objects inherit in a similar fashion as Ruby. But the thing that I couldn't really get was the way JavaScript was used in the example provided:

def ("Person") ({
    init: function(name){
        this.name = name;
    },

    speak: function(text){
        alert(text || "Hi, my name is " + this.name);
    }
});

def ("Ninja") << Person ({
    init: function(name){
        this._super();
    },

    kick: function(){
        this.speak("I kick u!");
    }
});

var ninjy = new Ninja("JDD");

ninjy.speak();
ninjy.kick();

in short, the two points are:

  1. def ("Person")({}); // parentheses after function call
  2. def ("Ninja") << Person ({}); // two function calls seperated by the operator <<

Is this a correct/legal use of JavaScript, and if it is, what's it's meaning i.e. how is interpreted by the browser.

Community
  • 1
  • 1
Azder
  • 4,698
  • 7
  • 37
  • 57

1 Answers1

2
def("Person")({...});

is basically chained function calls. It means:

  1. Pass the string "Person" to the function call def().
  2. def() returns a function which can then be called.
  3. Pass an object {...} as an argument to the function that is returned by def().

Not sure about the << operator as I've not encountered it in JS before. I would think it's the left bit-shift operator, but I don't know how it applies to functions.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    The `<<` operator is left shift. Since it doesn't know how to shift anything but a number, it calls `valueOf` on its operand. It's this `valueOf` function that sets up the inheritance, so any operator would probably do the same thing. – Gabe Dec 25 '10 at 08:03