我想从Car构造函数访问Vehicles的详细方法,并想通过调用打印名称和类型,而不是继承car内部的Vehicle。下面是我的代码:
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"));
但是我得到了以下错误:
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)
在调用newCar.details和call方法时,存在一些概念错误和错误。如果您能帮助我们解决问题,我们将不胜感激。
发布于 2020-07-15 14:33:50
call()的第一个参数应该是“调用func时使用的值”。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
至于继承:
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();
应该阅读:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
https://stackoverflow.com/questions/62916797
复制