【发布时间】:2020-03-08 21:01:20
【问题描述】:
如何将我的方法调用到其他对象? 我尝试过的所有事情都遇到了很多麻烦。 我对这些东西没有那么自信,只是在研究如何判断物体是否可以安全驾驶。
//Create a constructor function called `Track`. It will accept two parameters - the name of the track and the maximum capacity of the track.
let track = function(name, capacity){
this.trackName=name
this.personnel=0;
this.cars=[];
this.cap=capacity;
}
//We'll need a value for the average weight of a person but this value will be the same for all tracks.
//Add a property `personWeight` on the `Track` prototype so that all instances share the same value.
track.prototype.personWeight = 200
//Create three methods on the prototype that will calculate track weight, person weight, and if its safe to drive
function personWeight(){
personnelWeight = this.personWeight * this.personnel
return personnelWeight
}
function trackWeight(){
let carsTotal = function myFunc(total, num) {
return total - num;
}
let weightTotal = (this.personnel * this.personWeight) + (this.carsTotal)
return weightTotal
}
function safeToDrive(){
if(this.trackWeight<this.capacity){
return true
}
}
//Create two track objects
let trackOne = new track ("Daytona", 25000);
trackOne.cars = [1800, 2400, 2700, 3200, 3600, 3800, 4200]
trackOne.personnel = 10
let trackTwo = new track ("Indiana",15000);
trackTwo.cars = [2000, 2300, 2800, 3000, 3500, 3700, 4000]
trackTwo.personnel = 8
//Call the `safeToDrive` method for truck objects.
【问题讨论】:
-
请编辑和标记有问题的语言
-
您的方法不是您创建的对象跟踪的一部分。您的方法当前是在跟踪范围之外创建的。所以你必须像
safeToDrive();这样称呼他们。事情就是这样。由于它们不在跟踪范围内,this.personWeight可能未定义。
标签: javascript object methods