Чтобы визуально разделить пункты меню, можно задать каждому из них нижнюю или верхнюю границу. В зависимости от того, какую из них вы используете, у вас будет не хватать границы сверху или снизу меню. Это можно исправить, добавив еще одну границу к самому блоку.menu:
Menu a {
border-top: 1px solid blue;
}
.menu {
border-bottom: 1px solid blue;
}
Сейчас ссылки меню выглядят слишком низкими, расположенными близко друг к другу. Если текст каждой ссылки не будет занимать более одной строки, то увеличить их высоту и сохранить при этом текст вертикально по центру можно с помощью свойств height и line-height:
Как видно на анимации, свойство height влияет на высоту ссылки, а межстрочный интервал line-height изменяет уже высоту самой текстовой строки. Обязательно задавайте одинаковые значения для этих двух свойств, если хотите, чтобы текст ссылки был вертикально отцентрирован.
Основная задача при создании горизонтальной навигации - расположить пункты меню в один ряд. Это можно сделать несколькими способами.
Первый вариант - задать пунктам списка свойство display со значением inline либо inline-block:
После этого можно заняться оформлением ссылок. Например, можно сделать такой стиль:
Menu a {
text-decoration: none;
font-family: sans-serif;
color: #5757a0;
display: inline-block;
padding: 10px 20px;
background-color: lavender;
border-bottom: 5px solid #5757a0;
}
Мы добавили фоновый цвет и нижнюю границу для каждой ссылки, а также увеличили ее размеры при помощи внутренних отступов padding . Заметьте, что между пунктами меню есть небольшие промежутки, хоть мы и не добавляли их через стили. Они возникают, потому что браузер так воспринимает символ возврата каретки между закрывающим и открывающим тегами
:Menu li {
float: left;
}
Как видим, промежутков между пунктами уже нет. Все остальные стили работают, как и прежде. Но если вы добавите после навигации другой HTML-элемент (допустим,
), то на него повлияет обтекание и он встанет в один ряд с пунктами меню. Отменить это действие можно, добавив заголовку свойство clear: left . Но при разработке сайта с большим количеством разных страниц может стать сложно следить за тем, нигде ли вы не забыли указать данное свойство. Гораздо легче отменить обтекание со стороны навигации. В этом поможет такая запись:
Menu {
overflow: hidden;
}
Это также поможет вернуть нормальную высоту родителя плавающих элементов. Мы уже говорили об этой проблеме в предыдущих уроках, но тогда мы решали ее через специальный хак с использованием псевдоэлемента:after . Пример выше - это еще один способ решить вопрос с исчезнувшей высотой контейнера.
Примечание:
если вы установите фон для элемента.menu , то вы не увидите его до тех пор, пока не примените к нему overflow: hidden . Логично, ведь как можно увидеть фон элемента, чья высота равна нулю?
В следующем уроке мы более детально расскажем о возможностях селекторов атрибутов, с помощью которых можно задавать
Как объект языка Си, функцию необходимо объявить. Объявление функции пользователя, т.е. ее декларация, выполняется в двух формах – в форме описания и в форме определения.
Описание функции заключается в приведении вначале программного файла ее прототипа. Прототип функции сообщает компилятору о том, что далее в тексте программы будет приведено ее полное определение (полный ее текст): в текущем или другом файле исходного текста либо находится в библиотеке.
В стандарте языка используется следующий способ декларации функций:
тип_результата
ID_функции(тип переменной1, …, тип переменной N);
Заметим, что идентификаторы переменных в круглых скобках прототипа указывать не обязательно, так как компилятор языка их не обрабатывает.
Описание прототипа дает возможность компилятору проверить соответствие типов и количества параметров при фактическом вызове этой функции.
Пример описания функции fun со списком параметров:
float fun(int, float, int, int);
Полное определение функции имеет следующий вид:
тип_результата
ID_функции(список параметров)
код функции
Тип результата определяет тип выражения, значение которого возвращается в точку ее вызова при помощи оператора return <выражение>
.
Если тип функции не указан, то по умолчанию предполагается тип int
.
Список параметров состоит из перечня типов и идентификаторов параметров, разделенных запятыми.
Функция может не иметь параметров, но круглые скобки необходимы в любом случае.
Если функция не возвращает никакого значения, она должна быть описана как функция типа void
(пустая).
В данном случае оператор return
можно не ставить.
В функции может быть несколько операторов return
, но может и не быть ни одного. В таких случаях возврат в вызывающую программу происходит после выполнения последнего оператора в функции.
Пример функции, определяющей наименьшее значение из двух целочисленных переменных:
int min (int x, int y)
return (x
Все функции, возвращающие значение, должны использоваться в правой части выражений языка С, иначе возвращаемый результат будет утерян.
Если у функции отсутствует список параметров, то при декларации такой функции желательно в круглых скобках также указать ключевое слово void. Например, void main(void)
.
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure-a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
A method
is a function that is a property of an object. Read more about objects and methods in Working with objects .
Calling functions
Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling
the function actually performs the specified actions with the indicated parameters. For example, if you define the function square , you could call it as follows:
Square(5);
The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.
Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example:
Console.log(square(5));
/* ... */
function square(n) { return n * n; }
The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.
Note:
This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work. That means, function hoisting only works with function declaration and not with function expression.
Console.log(square); // square is hoisted with an initial value undefined.
console.log(square(5)); // Uncaught TypeError: square is not a function
var square = function(n) {
return n * n;
}
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props() function (defined in ) is an example of a function that takes an object as an argument.
A function can call itself. For example, here is a function that computes factorials recursively:
Function factorial(n) {
if ((n === 0) || (n === 1))
return 1;
else
return (n * factorial(n - 1));
}
You could then compute the factorials of one through five as follows:
Var a, b, c, d, e;
a = factorial(1); // a gets the value 1
b = factorial(2); // b gets the value 2
c = factorial(3); // c gets the value 6
d = factorial(4); // d gets the value 24
e = factorial(5); // e gets the value 120
There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the Function object). One of these, the apply() method, can be used to achieve this goal.
Function scope
Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.
// The following variables are defined in the global scope
var num1 = 20,
num2 = 3,
name = "Chamahk";
// This function is defined in the global scope
function multiply() {
return num1 * num2;
}
multiply(); // Returns 60
// A nested function example
function getScore() {
var num1 = 2,
num2 = 3;
function add() {
return name + " scored " + (num1 + num2);
}
return add();
}
getScore(); // Returns "Chamahk scored 5"
Scope and the function stack
Recursion
A function can refer to and call itself. There are three ways for a function to refer to itself:
- the function"s name
- an in-scope variable that refers to the function
For example, consider the following function definition:
Var foo = function bar() {
// statements go here
};
Within the function body, the following are all equivalent:
- bar()
- arguments.callee()
- foo()
A function that calls itself is called a recursive function
. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:
Var x = 0;
while (x < 10) { // "x < 10" is the loop condition
// do stuff
x++;
}
can be converted into a recursive function and a call to that function:
Function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:
Function walkTree(node) {
if (node == null) //
return;
// do something with node
for (var i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}
Compared to the function loop , each recursive call itself makes many recursive calls here.
It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.
The stack-like behavior can be seen in the following example:
Function foo(i) {
if (i < 0)
return;
console.log("begin: " + i);
foo(i - 1);
console.log("end: " + i);
}
foo(3);
// Output:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3
Nested functions and closures
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure
. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
- The inner function can be accessed only from statements in the outer function.
- The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
The following example shows nested functions:
Function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
a = addSquares(2, 3); // returns 13
b = addSquares(3, 4); // returns 25
c = addSquares(4, 5); // returns 41
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
Function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give
// it
result = fn_inside(5); // returns 8
result1 = outside(3)(5); // returns 8
Preservation of variables
Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside . The memory can be freed only when the returned inside is no longer accessible.
This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.
Multiply-nested functions
Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining
. (Why it is called "chaining" will be explained later.)
Consider the following example:
Function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // logs 6 (1 + 2 + 3)
In this example, C accesses B "s y and A "s x . This can be done because:
- B forms a closure including A , i.e. B can access A "s arguments and variables.
- C forms a closure including B .
- Because B "s closure includes A , C "s closure includes A , C can access both B and
A "s arguments and variables. In other words, C chains
the scopes of B and A in that order.
The reverse, however, is not true. A cannot access C , because A cannot access any argument or variable of B , which C is a variable of. Thus, C remains private to only B .
Name conflicts
When two arguments or variables in the scopes of a closure have the same name, there is a name conflict
. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:
Function outside() {
var x = 5;
function inside(x) {
return x * 2;
}
return inside;
}
outside()(10); // returns 20 instead of 10
The name conflict happens at the statement return x and is between inside "s parameter x and outside "s variable x . The scope chain here is { inside , outside , global object}. Therefore inside "s x takes precedences over outside "s x , and 20 (inside "s x) is returned instead of 10 (outside "s x).
Closures
Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.
Var pet = function(name) { // The outer function defines a variable called "name"
var getName = function() {
return name; // The inner function has access to the "name" variable of the outer
//function
}
return getName; // Return the inner function, thereby exposing it to outer scopes
}
myPet = pet("Vivie");
myPet(); // Returns "Vivie"
It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.
Var createPet = function(name) {
var sex;
return {
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
},
getSex: function() {
return sex;
},
setSex: function(newSex) {
if(typeof newSex === "string" && (newSex.toLowerCase() === "male" ||
newSex.toLowerCase() === "female")) {
sex = newSex;
}
}
}
}
var pet = createPet("Vivie");
pet.getName(); // Vivie
pet.setName("Oliver");
pet.setSex("male");
pet.getSex(); // male
pet.getName(); // Oliver
In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.
Var getCode = (function() {
var apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify...
return function() {
return apiCode;
};
})();
getCode(); // Returns the apiCode
There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.
Var createPet = function(name) { // The outer function defines a variable called "name".
return {
setName: function(name) { // The enclosed function also defines a variable called "name".
name = name; // How do we access the "name" defined by the outer function?
}
}
}
Using the arguments object
The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:
Arguments[i]
where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments . The total number of arguments is indicated by arguments.length .
Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don"t know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.
For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
Function myConcat(separator) {
var result = ""; // initialize list
var i;
// iterate through arguments
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
You can pass any number of arguments to this function, and it concatenates each argument into a string "list":
// returns "red, orange, blue, "
myConcat(", ", "red", "orange", "blue");
// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
Note:
The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.
Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this .
Shorter functions
In some functional patterns, shorter functions are welcome. Compare:
Var a = [
"Hydrogen",
"Helium",
"Lithium",
"Beryllium"
];
var a2 = a.map(function(s) { return s.length; });
console.log(a2); // logs
var a3 = a.map(s => s.length);
console.log(a3); // logs
No separate this
Until arrow functions, every new function defined its own value (a new object in the case of a constructor, undefined in function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.
Function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0;
setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.
Function Person() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}