Help with understanding a function

Hello,

I am a beginner JS student. I am having trouble understanding the code below. If someone could explain it line by line. Thank you in advance!

var Car = function() {
  this.gear = 1;
  function addStyle(styleMe){
    return 'The Current Gear Is: ' + styleMe;
  }
  this.getGear = function() {
    return addStyle(this.gear);
  };
};

Creates a variable called Car that contains a function. By common convention, variables with a capital first letter are intended to be used to create new objects. In this case, it would be with:

var car = new Car();

The this keyword refers to the current object, which in this case is the function that will be assigned to the Car variable. Here we are giving that function a property called gear, which we intend to use to keep track of which gear the car is in.

When a value is added to an object, that is called a property of that object. When it’s a function that’s added to the object, it’s instead called a method of that object. The same goes for when they are added to a function too.

[quote=“serhiicss, post:1, topic:205592, full:true”] function addStyle(styleMe){
[/quote]

Creates a function that accepts one argument called styleMe. The function is internal to the Car one, that only the Car function will be able to use. The addStyle name of the function is a generic term, that means you’re going to add some additional stuff to what is given.

[quote=“serhiicss, post:1, topic:205592, full:true”] return 'The Current Gear Is: ’ + styleMe;
[/quote]

Returns a string value from the addStyle function. In this case the text inside of the single quotes is the added style. Which is appended before the styleMe argument.

[quote=“serhiicss, post:1, topic:205592, full:true”] }
[/quote]

Defines the end of the addStyle function.

[quote=“serhiicss, post:1, topic:205592, full:true”] this.getGear = function() {
[/quote]

Add a method to the Car function that is intended to be used to get the gear that the car is in.

[quote=“serhiicss, post:1, topic:205592, full:true”] return addStyle(this.gear);
[/quote]

Returns a nicely styled text saying what gear the car is in.

[quote=“serhiicss, post:1, topic:205592, full:true”] };
[/quote]

Defines the end of the addStyle method.

[quote=“serhiicss, post:1, topic:205592, full:true”] };
[/quote]

Defines the end of the car object.

A way to use the above code, could be to create a new car object, set its gear, then show what gear the car is in.

var car = new Car();
car.gear += 1;
alert(car.getGear()); // The Current Gear Is: 2
2 Likes

Wow! You are amazing! I could not ask for a better explanation. Thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.