gpt4 book ai didi

javascript - 自行车构造器不断添加齿轮而不是输出指定数量

转载 作者:行者123 更新时间:2023-12-03 16:41:47 24 4
gpt4 key购买 nike

我目前正在学习 Javascript 并在 freecodecamp 学习基础 OOP .此时,我正在创建一个对象,并试图让该对象返回我希望它返回的内容。

这个项目的完整描述是:

Objects have their own attributes, called properties, and their own functions, called methods.

In the previous challenges, we used the this keyword to reference public properties of the current object.

We can also create private properties and private methods, which aren't accessible from outside the object.

To do this, we create the variable inside the constructor using the var keyword we're familiar with, instead of creating it as a property of this.

This is useful for when we need to store information about an object but we want to control how it is used by outside code.

For example, what if we want to store the speed our car is traveling at but we only want outside code to be able to modify it by accelerating or decelerating, so the speed changes in a controlled way?

In the editor you can see an example of a Car constructor that implements this pattern.

Now try it yourself! Modify the Bike constructor to have a private property called gear and two public methods called getGear and setGear to get and set that value.

现在我明白了它是如何工作的基本概念,我也明白我在做什么,但是我也在使用 node terminal 来尝试自己调试它,我已经得出程序每次都将齿轮加在一起的结论:

> var Bike = function() {
...
... // Only change code below this line.
... var gear = 0;
...
... this.setGear = function(switchGear){
... gear += switchGear;
... };
...
... this.getGear = function() {
... return gear;
... };
... };
undefined
> var myBike = new Bike();
undefined
> myBike.setGear(4);
undefined
> myBike.getGear();
4
> myBike.setGear(4);
undefined
> myBike.getGear();
8
>

有人可以向我解释我在这里做错了什么吗?我不明白为什么要加在一起..谢谢..

来源:

var Bike = function() {

// Only change code below this line.
var gear = 0;

this.setGear = function(switchGear){
gear += switchGear;
};

this.getGear = function() {
return gear;
};
};

var myBike = new Bike();

最佳答案

我想这对软件中的所有错误都是正确的,但它正在这样做因为你告诉它!

gear += switchGear;

你说,把这个值加到齿轮上,它确实做到了。

编辑:OP 的评论使他的困惑更加清晰。

他似乎认为 gear 的值应该以某种方式“重置”,并归零。

不,当 new Bike() 被调用时,函数 Bike 中的步骤只运行一次。变量 gear 持续存在,并且它的值仅在通过方法更改时更改。

关于javascript - 自行车构造器不断添加齿轮而不是输出指定数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36892453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com