1

I'm following this melon JS tutorial, and am on part 3.

I am not clear on a couple things in this code snippet

game.PlayerEntity = me.ObjectEntity.extend({

    init: function(x, y, settings) {
        this.parent(x, y, settings);
        ... more code here       
    },

Firstly, you're creating a new member in my "game" object called "PlayerEntity" which extends the melonJS (me) Object Entity class. I get that. But I don't understand

1) is the this referring to "game" object?

2) If so, then this.parent would be referring to the parent of "game"- is this just the ObjectEntity class that it's inheriting from?

3) Why can't I call this from outside game object as such? It's saying it has no method init even though I've defined one in game.PlayerEntity {} object.

game.PlayerEntity.init(1, 2, 3);

4) if you're calling the constructor with this.parent(x, y, settings), where are x, y, settings parameters being set? With Java, you call a constructor as such:

public Bicycle(int val1, int val2) {
    myVal1 = val1;
    myVal2 = val2;
}

then create new instance of class:

Bicycle bike = new Bicycle(1, 2);

Therefore the constructor of Bicycle is being called when you create the instance.

But with this, It's not clear to me how this.parent(x, y, settings); is "calling the constructor".

Thanks!

Dan
  • 9,391
  • 5
  • 41
  • 73
user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

1

This convention was originally described by John Resig. In fact, it even mentions him in the melonJS documentation.

The inheritance taking place is where the .parent derivation is coming in to play. Basically what is happening is this is referring to your current object, PlayerEntity in this case.

extend is not a built in function and does do some things behind the scenes - one of which is to modify the property .parent to refer to the "super class". You can see this in the source code

Object.extend = function(prop) {
    // _super rename to parent to ease code reading
    var parent = this.prototype;

Since PlayerEntity essentially extended ObjectEntity, what is happening during this call

this.parent(x, y, settings);

is that ObjectEntity is being called with those 3 parameters (x,y,settings) to construct the underlying properties and state using inheritance.

melonJS source code on github: https://github.com/melonjs/melonJS/blob/master/src/core.js

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • Awesome! thanks. Few more questions. 1) Where are `x, y, settings` params being defined though? 2)To preserve inheritance, can't I just use `ObjectEntity.apply(this, arguments);` within PlayerEntity? 3) How is `init` called? I didn't find `init` as a member of ObjectEntity class here http://melonjs.github.io/docs/me.ObjectEntity.html – user3871 Mar 14 '14 at 02:38