A. M. Mérida
A. M. Mérida

Reputation: 2618

Extract data from an object in javascript

I have a "class" defined:

function Car(door, engine) {
    this.door = door;
    this.engine = engine;

    function setDoor(door) {
        this.door = door;
    }
    function getDoor(door) {
        return door;
    }
    function setEngine(engine) {
        return engine;
    }
    function getEngine() {
        return engine;
    }
}

I want to extract data from an object in javascript, in the same file I have another "class" and the function to add.

function bodyCar(car) {
    newCar = new Array();
    function addCar(car) {
        newCar = car.door;
        newCar = car.engine;
        return "The new car have " + car.door + " doors. engine " + car.engine;
    }
}

the call to the class and function:

var myCar = new bodyCar();
myCar.addCar(new Car(5,"2200cc"));
document.write(myCar);

But it does not work for me. It gives a type error "myCar.addCar is not a function".

thanks for your help.

Upvotes: 0

Views: 104

Answers (2)

julian soro
julian soro

Reputation: 5228

If you're trying to create OOP-style class methods, then you have some options:

create a function property of the class

function bodyCar(car) {
  newCar = new Array();
  this.addCar = function(car) {
    // do addCar method stuff here
  }
}

or if you want to use the prototype method approach (better memory management)

function bodyCar(car) {
  newCar = new Array();
}

bodyCar.prototype.addCar = function(car) {
    // do addCar method stuff here
}

Likewise, the same approach should be used for the methods on your base car class, like setDoor and getDoor etc.

Further, if you want OOP-style "inheritance", you should opt for the prototype approach, and use Object.create()

Good luck!

Upvotes: 2

Mark Reed
Mark Reed

Reputation: 95242

That's not how you define methods in class-style Javascript. The functions you define inside the constructor function only exist during the call to the constructor.

If you want to add "instance methods" to the "class", you have to put them on the constructor function's prototype object:

function Car(door, engine) {
  this.door = door;
  this.engine = engine;
}

Car.prototype.setDoor = function(door) {
  this.door = door;
}

Car.prototype.getDoor = function() {
  return this.door;
}

Car.prototype.setEngine = function(engine) {
  this.engine = engine;
}

Car.prototype.getEngine = function() {
  return this.engine;
}

That said, your logic in the second class (creating and then throwing away an Array) doesn't make sense to me; I'm not sure what your actual goal is. But hopefully the above helps get you closer.

Upvotes: 2

Related Questions