Methods and properties

Lecture




  1. Example: str.length , str.toUpperCase()
  2. Example: num.toFixed

All values ​​in JavaScript, with the exception of null and undefined , contain a set of auxiliary functions and values ​​accessible "through the dot".

Such functions are called "methods", and values ​​- "properties". Let's look at examples.

Example: str.length , str.toUpperCase()

The string has a length property that contains a length:

1 alert( "Привет, мир!" .length ); // 12

Strings also have a toUpperCase() method that returns an uppercase string:

1 var hello = "Привет, мир!" ;
2
3 alert( hello.toUpperCase() ); // "ПРИВЕТ, МИР!"

If a function is called through a point ( toUpperCase() ), this is called a “method call” if you simply read the value ( length ) - “property retrieval”.

Example: num.toFixed

Numbers have a num.toFixed(n) method. It rounds the number num to n decimal places, if necessary, finishes with zeros to a given length and returns as a string (conveniently for formatted output):

1 var n = 12.345;
2
3 alert( n.toFixed(2) ); // "12.35"
4 alert( n.toFixed(0) ); // "12"
5 alert( n.toFixed(5) ); // "12.34500"

The details of the toFixed work are toFixed in the Numbers chapter

Appeal to methods of numbers

The number method can also be addressed directly:

1 alert( 12.34.toFixed(1) ); // 12.3

... But if the number is an integer, then there will be a problem:

1 alert( 12.toFixed(1) ); // ошибка!
The error will occur because JavaScript expects a decimal after a point.

This is a feature of JavaScript syntax. This is how it will work:

1 alert( 12..toFixed(1) ); // 12.0

The method call is through parentheses!

Pay attention, for the method call after its name there are brackets: hello.toUpperCase() . Without brackets the method will not be called.

Let's see, for example, the result of a call to toUpperCase without brackets:

1 var hello = "Привет" ;
2
3 alert( hello.toUpperCase ); // function...

This code displays the value of the toUpperCase property, which is a function embedded in the language. Typically, the browser displays it something like this: "function toUpperCase() { [native code] }" .

To get the result, this function must be called, and just for this in JavaScript brackets are required:

1 var hello = "Привет" ;
2
3 alert( hello.toUpperCase() ); // "ПРИВЕТ" (результат вызова)

We will meet with lines and numbers in later chapters and learn more about the means to work with them.

created: 2014-10-07
updated: 2021-03-13
132492



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone