【问题标题】:How do I call a method to an object?如何调用对象的方法?
【发布时间】: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


【解决方案1】:

使用现在的代码,您可以使用safeToDrive.call(trackOne)。但是,这不是您通常会做的直接方式。

我猜你真正想要的是将这些方法分配给原型:

    track.prototype.safeToDrive = function () {
        if(this.trackWeight<this.capacity){
            return true 
        }
    }

然后你会使用trackOne.safeToDrive()给他们打电话。

personWeighttrackWeight 也是如此。


其他一些观察:

  1. 您对this.capacity 的检查将不起作用,因为根据您在构造函数中设置的内容,该属性实际上被称为cap 而不是capacity

  2. safeToDrive 当前返回 true 或什么都不返回,即 undefined,而不是您所期望的 truefalse

    您可以通过添加 elsereturn false 或简单地使用 return this.trackWeight &lt; this.capacity 而不是整个 if 条件来解决此问题。

  3. 哦,另外,您的 personnelWeight 变量意外地变成了全局变量。在它之前添加一个let。首先要避免这种情况,请在文件顶部添加'use strict',以便下次收到有关此问题的警告。

  4. 1234563 .另外,你的缩进是错误的。 (通过beautifier 发送您的文件以了解我的意思。)
  5. 你的意思是truck而不是track也许...?

【讨论】:

  • 这样吗? console.log(trackOne.safeToDrive()) ,卡车的重量应该是数组的总和。
猜你喜欢
  • 2012-01-25
  • 1970-01-01
  • 2014-04-12
  • 2016-02-11
  • 1970-01-01
  • 2016-06-08
  • 2011-12-10
  • 2015-03-20
  • 2021-12-28
相关资源
最近更新 更多