Xameer
Xameer

Reputation: 31237

Why is the function prototype not working in this fiddle?

I was trying to print values of vehicle object in my fiddle using javascript function prototypes.

function carDetails() {
  var car = new vehicle("Red", "Car");
  car.getPrice(100);

  // Define a function which will work as a method
  vehicle.prototype.price = function getPrice(amount) {
    car.price = amount;
  };

  document.getElementById("color").innerHTML = car.color;
  document.getElementById("type").innerHTML = car.type;
  document.getElementById("price").innerHTML = car.price;

}

function vehicle(color, type) {
  this.color = color;
  this.type = type;
  //this.prototype.price = getPrice;
}

vehicle.prototype.getPrice = getPrice;

carDetails();
<h1>
Javascript function prototypes
</h1>
<p id='color'></p>

<p id='type'></p>

<p id='price'></p>

Why is the vehicle object not getting printed?

Upvotes: 1

Views: 121

Answers (2)

sundar
sundar

Reputation: 408

function carDetails() {
  var car = new vehicle("Red", "Car");
  car.getPrice(100);

  document.getElementById("color").value = car.color;
  document.getElementById("type").value = car.type;
  document.getElementById("price").value = car.price;

}

// Define a function which will work as a method
function getPrice(amount) {
  this.price = amount;
}


function vehicle(color, type) {
  this.color = color;
  this.type = type;
  this.getPrice = getPrice;
}

carDetails();

It will work

Upvotes: 1

Ramanlfc
Ramanlfc

Reputation: 8354

function vehicle(color, type) {
  this.color = color;
  this.type = type;
  this.price = getPrice;
}

 car.getPrice(100);

the property is price in and your using getPrice().

Also , set set functions on prototype to avoid functions objects from being created with each constructor call.

Upvotes: 2

Related Questions