Reputation: 1541
I want to access the details method of Vehicles from car constructor and want to print the name and type by calling without inheriting the Vehicles inside Car. Here's my code:
function Vehicles(name, type) {
// console.log(name);
this.name = name;
this.type = type;
this.getDetails = function() {
console.log(this.name, this.type);
}
}
function car(name, type) {
this.NewVehicles = new Vehicles(name, type);
// this.details = this.call(this.NewVehicles.getDetails);
this.details = this.NewVehicles.call(this.getDetails);
}
const newCar = new car();
console.log(newCar.details("ss", "zxxzx"));
But I'm getting the following error:
this.details = this.NewVehicles.call(this.getDetails); ^
TypeError: this.NewVehicles.call is not a function
at new car (/temp/file.js:16:35)
at Object.<anonymous> (/temp/file.js:19:16)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Some miss-conceptions, some mistakes are there while calling newCar.details and the call method. Any help would be appreciated for resolving the issue.
Upvotes: 0
Views: 46
Reputation: 72
First parameter of call() should be "The value to use as this when calling func." See : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
As for the inheritance :
function Vehicle(name, type) {
this.name = name;
this.type = type;
this.getDetails = function() {
console.log(this.name, this.type);
}
}
function Car(name, type) {
Vehicle.call(this, name, type);
}
const myCar = new Car("foo", "bar");
myCar.getDetails();
Should read : https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
Upvotes: 1