Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Oriented Javascript - How To Define A Class Within A Class? from a C# example

Tags:

javascript

oop

I know there are a lot of OO javascript questions on SO and I a have been reading a lot of resources.... BUT it is still far my most long winded learning curve so far!

I am not classically trained sorry, hence I will have to just show you guys in c# an example of what I want to acheive.

I hope you can help!

public class Engine
{
    public int EngineSize;

    public Engine()
    {
    }
}
public class Car
{
    public Engine engine;

    public Car()
    {
        engine = new Engine();
    }
}

guys I am not really worried about the private/public & naming conventions of the above C# example.

All I want to know is how to replicate this structure in Javascript?

Thanks!

like image 898
divinci Avatar asked Aug 24 '09 15:08

divinci


1 Answers

function Engine(size) {
    var privateVar;

    function privateMethod () {
      //...
    }

    this.publicMethod = function () {
       // with access to private variables and methods
    };

    this.engineSize = size; // public 'field'
}

function Car() { // generic car
    this.engine = new Engine();
}

function BMW1800 () {
  this.engine =  new Engine(1800);
}

BMW1800.prototype = new Car(); // inherit from Car


var myCar = new BMW1800();
like image 101
Christian C. Salvadó Avatar answered Nov 12 '22 10:11

Christian C. Salvadó