JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

JavaScript функц нь тодорхой даалгаврыг гүйцэтгэхэд зориулагдсан кодын блок юм.

A JavaScript function is executed when “something” invokes it (calls it).

JavaScript функцийг “ямар нэг зүйл” дуудах үед (үүнийг дууддаг) гүйцэтгэдэг.


Example Жишээ #

function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2 }

JavaScript Function Syntax #

JavaScript функцын синтакс #

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

JavaScript функцийг function түлхүүр үгээр тодорхойлж дараа нь нэр, дараа нь хаалт () оруулна.

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

Функцийн нэрэнд үсэг, цифр, доогуур зураас, долларын тэмдэг байж болно (хувьсагчтай ижил дүрмүүд).

The parentheses may include parameter names separated by commas:

Хаалтанд параметрийн нэрийг таслалаар тусгаарласан байж болно:

(parameter1, parameter2, …)

The code to be executed, by the function, is placed inside curly brackets: {}

Ажиллах кодыг функцээр нь буржгар хаалтанд байрлуулна: {}

function name(parameter1, parameter2, parameter3) { // code to be executed }

Function parameters are listed inside the parentheses () in the function definition.

Функцийн параметрүүдийг хаалт дотор () функцын тодорхойлолтонд жагсаав.

Function arguments are the values received by the function when it is invoked.

Функцийн аргументууд нь функцийг дуудахад хүлээн авсан утгууд юм.

Inside the function, the arguments (the parameters) behave as local variables.

Функц дотор аргументууд (параметрүүд) нь локал хувьсагчийн үүрэг гүйцэтгэдэг.

A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Функц нь бусад програмчлалын хэл дээр процедур эсвэл дэд програмтай адилхан байдаг.


Function Invocation #

Функцийн дуудлага #

The code inside the function will execute when “something” invokes (calls) the function:

Функц доторх код нь “ямар нэг зүйл” функцийг invokes (дуудах) үед гүйцэтгэх болно.

  • When an event occurs (when a user clicks a button)

    Үйл явдал тохиолдох үед (хэрэглэгч товчлуур дээр дарахад)

  • When it is invoked (called) from JavaScript code

    Энэ нь JavaScript кодоос дуудагдсан (дуудагдсан) үед

  • Automatically (self invoked)

    Автоматаар (өөрөө дууддаг)

You will learn a lot more about function invocation later in this tutorial.

Та энэ гарын авлагын дараа функцийн дуудлагын талаар илүү ихийг олж мэдэх болно.


 
 
 

Function Return #

Чиг үүрэг буцах #

When JavaScript reaches a return statement, the function will stop executing.

JavaScript нь буцах мэдэгдэлд хүрэхэд функц нь ажиллахаа болино.

If the function was invoked from a statement, JavaScript will “return” to execute the code after the invoking statement.

Хэрэв функц нь мэдэгдэл дээр дуудагдсан бол JavaScript нь дуудлага хийсний дараа кодыг ажиллуулахын тулд “буцах” болно.

Functions often compute a return value. The return value is “returned” back to the “caller”:

Функцууд нь ихэвчлэн буцах утгыг тооцоолдог. Буцах утга нь “дуудагч” руу буцаж “буцаж” орно.

Example Жишээ #

Calculate the product of two numbers, and return the result:

Хоёр тооны үржвэрийг тооцоолоод үр дүнг буцаана.

var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { return a * b; // Function returns the product of a and b }

The result in x will be:

X-ийн үр дүн нь:

12

Why Functions? #

You can reuse code: Define the code once, and use it many times.

Та кодыг дахин ашиглаж болно: Кодыг нэг удаа тодорхойлж, олон удаа ашиглаарай.

You can use the same code many times with different arguments, to produce different results.

Та өөр кодыг олон удаа янз бүрийн аргумент ашиглан ашиглаж болно.

Example Жишээ #

Convert Fahrenheit to Celsius:

Фаренгейтийг Цельсийн болгож хөрвүүлэх:

function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius(77);

The () Operator Invokes the Function #

() Оператор функцийг дууддаг #

Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Дээрх жишээг ашиглан toCelsius нь функцийн объектыг, toCelsius() нь функцийн үр дүнг хэлнэ.

Accessing a function without () will return the function object instead of the function result.

() Байхгүй функцэд хандах нь функцын үр дүнгийн оронд функцийн объектыг буцааж өгөх болно.

Example Жишээ #

function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;

Functions Used as Variable Values #

Хувьсах утга болгон ашигладаг функцууд #

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Функцийг бүх төрлийн томъёо, даалгавар, тооцоонд хувьсагч ашиглаж байгаатай адил ашиглаж болно.

Example Жишээ #

Instead of using a variable to store the return value of a function:

Функцийн өгөөжийн утгыг хадгалахын тулд хувьсагч ашиглахын оронд:

var x = toCelsius(77); var text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

Та функцийг хувьсах утга болгон шууд ашиглаж болно.

var text = "The temperature is " + toCelsius(77) + " Celsius";

You will learn a lot more about functions later in this tutorial.

Та энэхүү гарын авлагын дараа функцүүдийн талаар илүү их зүйлийг сурч мэдэх болно.


Local Variables #

Орон нутгийн хувьсагчууд #

Variables declared within a JavaScript function, become LOCAL to the function.

JavaScript функцэд зарлагдсан хувьсагчид тухайн функцэд LOCAL болно.

Local variables can only be accessed from within the function.

Жижиг хувьсагчуудад зөвхөн функц дотроос хандах боломжтой.

// code here can NOT use carName function myFunction() { var carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Локал хувьсагчийг зөвхөн функц дотроос нь хүлээн зөвшөөрдөг тул ижил нэртэй хувьсагчуудыг өөр өөр функцэд ашиглаж болно.

Local variables are created when a function starts, and deleted when the function is completed.

Дотоод хувьсагчууд нь функц эхлэхэд үүсдэг бөгөөд функц дуусахад устгагдана.

Powered by BetterDocs

Leave a Reply