简体   繁体   中英

Does a setter function's parameter name needs to be different from a private variable in javascript?

Why does the constructor function return preset/initial value for this code?

I am calling the setGear() with a value of 5 yet getGear() returns 1 instead of 5.

This can be fixed by changing the parameter name in the setGear() function to anything other than 'gear'.

var Bike = function() {
     var gear = 1;

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

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

 ////////
 var myBike = new Bike();
 myBike.setGear(5);
 result = myBike.getGear();

This is because you are using same variable name gear in your set Gear method. when you call the function setGear( gear ), gear will take the value of local variable gear defined in the Bike function.

change the variable name to something different for example input

 var Bike = function() { var gear = 1; this.getGear = function() { return gear; }; this.setGear = function(input) { gear = input; }; }; //////// var myBike = new Bike(); myBike.setGear(5); result = myBike.getGear(); console.log(result);

A parameter name is a local symbol in the function. It hides any variables with the same name in outer scopes. In the .getGear() function, the symbol gear refers to the variable declared in the constructor function. However, because .setGear() has a parameter also named gear , that outer gear is not accessible.

If you think about it, in that assignment:

gear = gear;

it would be pretty bizarre if one gear were one thing while the other was something else.

with gear = gear you are assigning the value to the parameter 'gear' not the class member. To avoid confusion, simply rename your parameter.

 var Bike = function() {
 var gear;
 this.gear = 1;

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

 this.setGear = function(gear) {
     this.gear = gear;
 };
};
////////
var myBike = new Bike();
myBike.setGear(5);
result = myBike.getGear();

Use this keyword to access gear variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM