Jump to content

How to Create an object class (OOP)


aladine
 Share

Recommended Posts

Hello everyone, 

Am not familiar with advanced JS programming, so this might be a super noob question for you  :rolleyes:

 

in object oriented languages, most of the time when we want to create an enemy, we define a class that contain all the enemy parameters (speed,health,power,etc...) and then we control those values with gets and sets after creating an instance of that class in our main game class.

 

Am asking for an alternative way to do the same thing with JavaScript (am using Phaser), my enemy must have Speed and Image variable that change depend on his state, and of course i have more than one enemy so.... Help please   :D

 

thank you 

 

Link to comment
Share on other sites

Javascript does not have OOP like you would normally see in Java, .NET, PHP etc. Classes do not exist!

Instead, javascript uses "prototypes", that means composition is used over inheritance. Unfortunately Javascript does have constructors, thats exacylu what makes it so hard to understand for beginners and hard to explain by us.. It's also called "pseudo-classical" because of this...  :blink:

 

 

This is a constructor:

 

function Enemy(name, health) {

    this.name = name;

    this.health = health;

}

 

var myEnemy = new Enemy('enemy name', 1000);

 

Enemy.prototype.instanceMethod = function() {}

 

Enemy.StaticProperty = 'foo';

 

You can play with the prototype property (hence composition) in order to change the parent. Or you can inject methods/properties using mixins http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/

 

If you would like some "OOP sugar" I would suggest you take a look at either Coffeescript or Typescript, they allow you to write "classes, interfaces etc" which will be compiled down to boilerplate code in plain JS. Otherwise you can always implement a solution like http://classy.pocoo.org, which is also simple to write yourself.

 

Back on track; why would you want to stuff al the parameters inside a javascript object? You should take a look at what the "entity-component-system" design tries to solve. Im not sure of whether phaser will play nice along with ECS :) (@see: http://www.richardlord.net/blog/why-use-an-entity-framework)

 

Hope I helped you atleast a little bit, I know it's hard to digest at first sight!  :D

Link to comment
Share on other sites

In JS you work with objects directly, you don't have to instantiate them from class templates like you do in other OOP languages.

But sometimes it's useful to create a template object with some default properties that you can use to make other objects with.

In JS a template object is called a prototype.

 

First, just make a an object with some useful properties.

Give it a `make` method so that you can use it as a base to make new, customized objects:

 

var rectangle = {
    type: "rectangle",
    x: 0,
    y: 0,
    width: 64,
    height: 64,
    rotation: 0,
    alpha: 1,
    visible: true,
    strokeStyle: "black",
    lineWidth: 1,
    fillStyle: "rgba(128, 128, 128, 1)",
    get halfWidth() {
      return this.width / 2;
    },
    get halfHeight() {
      return this.height / 2;
    },
    get center() {
      return {
        x: this.x + this.halfWidth,
        y: this.y + this.halfHeight
      }
    },
    make: function(config) {
      var newObject = Object.create(this);
      //If a config object has been used to initialize the
      //sprite, assign those values to the new object
      if (config !== undefined) {
        Object.keys(config).forEach(function(key) {
          newObject[key] = config[key];
        });
      }
      return newObject;
    }
  };
 
You can now make a new custom object like this:
 
var box = rectangle.make({
    x: 80,
    y: 100,
    width: 120,
    height: 80,
    fillStyle: "rgba(105, 210, 231, 1)",
    strokeStyle: "red",
    rotation: 0.5,
    //New properties:
    vx: 2,
    vy: 3
  });
 
(The rectangle is now the prototype for the box.)
You can add any new properties or methods to it that you like.
 
The box is not a copy of the rectangle: its properties just mask the rectangle's properties.
If the box hasn't over-written any of the rectangle's properties, like lineWidth, the prototype rectangle's properties will be used.
Link to comment
Share on other sites

JavaScript is different from classical object oriented programming languages like C++ and Java.  I highly recommend looking at Douglas Crockford's videos on JavaScript, starting with his general overview of the language, see: http://www.youtube.com/watch?v=v2ifWcnQs6M.

 

JavaScript uses prototypical inheritance and it is very important that you understand how it works if you want to write code with it.  

 

As other have said something like:

 

function Player(x,y) {

    this.x = x;

    this.y = y;

}

 

Player.prototype.move = function(x, y) { this.x = x; this.y; }

 

var player = new Player(0,0)

player.move(10,10)

 

It's a good start, but there is more to learn than that, such as:

  • How to share code between different objects
  • How to make it so that all you game objects are not global
  • How to protect internal member variable from being accessed directly
  • How to handle handle costly operations without blocking the UI, since JavaScript is single threaded in the browser
  • etc..
Link to comment
Share on other sites

 

It's a good start, but there is more to learn than that, such as:

  • How to share code between different objects
  • How to make it so that all you game objects are not global
  • How to protect internal member variable from being accessed directly
  • How to handle handle costly operations without blocking the UI, since JavaScript is single threaded in the browser
  • etc..

 

yes exactly, am feeling very confused and even scared when i think about making a "big" game, am even reconsidering the TypeScript option just because it allow me to code like am used to.

Am going to watch the video you linked in the post, it looks pretty helpful

thanx  

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...