From 1482bfc52b65c028c364670ab9f2561e7660a932 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 18:04:56 +0300 Subject: Add not translated verson of javasript --- ru-ru/javascript-ru.html.markdown | 529 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 529 insertions(+) create mode 100644 ru-ru/javascript-ru.html.markdown (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown new file mode 100644 index 00000000..7e2c0cca --- /dev/null +++ b/ru-ru/javascript-ru.html.markdown @@ -0,0 +1,529 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["--mynamehere--", "http://github.com/--mynamehere--"] +filename: javascript-ru.js +lang: ru-ru +--- + +JavaScript was created by Netscape's Brendan Eich in 1995. It was originally +intended as a simpler scripting language for websites, complementing the use of +Java for more complex web applications, but its tight integration with Web pages +and built-in support in browsers has caused it to become far more common than +Java in web frontends. + +JavaScript isn't just limited to web browsers, though: Node.js, a project that +provides a standalone runtime for Google Chrome's V8 JavaScript engine, is +becoming more and more popular. + +Feedback would be highly appreciated! You can reach me at +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ + +// Statements can be terminated by ; +doStuff(); + +// ... but they don't have to be, as semicolons are automatically inserted +// wherever there's a newline, except in certain cases. +doStuff() + +// Because those cases can cause unexpected results, we'll keep on using +// semicolons in this guide. + +/////////////////////////////////// +// 1. Numbers, Strings and Operators + +// JavaScript has one number type (which is a 64-bit IEEE 754 double). +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. +3; // = 3 +1.5; // = 1.5 + +// Some basic arithmetic works as you'd expect. +1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Including uneven division. +5 / 2; // = 2.5 + +// Bitwise operations also work; when you perform a bitwise operation your float +// is converted to a signed int *up to* 32 bits. +1 << 2; // = 4 + +// Precedence is enforced with parentheses. +(1 + 3) * 2; // = 8 + +// There are three special not-a-real-number values: +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 + +// There's also a boolean type. +true; +false; + +// Strings are created with ' or ". +'abc'; +"Hello, world"; + +// Negation uses the ! symbol +!true; // = false +!false; // = true + +// Equality is === +1 === 1; // = true +2 === 1; // = false + +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true + +// More comparisons +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings are concatenated with + +"Hello " + "world!"; // = "Hello world!" + +// and are compared with < and > +"a" < "b"; // = true + +// Type coercion is performed for comparisons with double equals... +"5" == 5; // = true +null == undefined; // = true + +// ...unless you use === +"5" === 5; // = false +null === undefined; // = false + +// You can access characters in a string with charAt +"This is a string".charAt(0); // = 'T' + +// ...or use substring to get larger pieces +"Hello world".substring(0, 5); // = "Hello" + +// length is a property, so don't use () +"Hello".length; // = 5 + +// There's also null and undefined +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although + // undefined is actually a value itself) + +// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". + +/////////////////////////////////// +// 2. Variables, Arrays and Objects + +// Variables are declared with the var keyword. JavaScript is dynamically typed, +// so you don't need to specify type. Assignment uses a single = character. +var someVar = 5; + +// if you leave the var keyword off, you won't get an error... +someOtherVar = 10; + +// ...but your variable will be created in the global scope, not in the scope +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar; // = undefined + +// There's shorthand for performing math operations on variables: +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++; // now someVar is 101 +someVar--; // back to 100 + +// Arrays are ordered lists of values, of any type. +var myArray = ["Hello", 45, true]; + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1]; // = 45 + +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + +// Add/Modify at specific index +myArray[3] = "Hello"; + +// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// languages: an unordered collection of key-value pairs. +var myObj = {key1: "Hello", key2: "World"}; + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Object attributes can also be accessed using the subscript syntax, +myObj["my other key"]; // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey; // = "myValue" + +// Objects are mutable; values can be changed and new keys added. +myObj.myThirdKey = true; + +// If you try to access a value that's not yet set, you'll get undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logic and Control Structures + +// The syntax for this section is almost identical to Java's. + +// The if structure works as you'd expect. +var count = 1; +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4){ + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} + +// As does while. +while (true){ + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// the for loop is the same as C and Java: +// initialisation; continue condition; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + +// switch statement checks for equality with === +// use 'break' after each case +// or the cases after the correct one will be executed too. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript functions are declared with the function keyword. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Note that the value to be returned must start on the same line as the +// 'return' keyword, otherwise you'll always return 'undefined' due to +// automatic semicolon insertion. Watch out for this when using Allman style. +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. + +// Function objects don't even have to be declared with a name - you can write +// an anonymous function definition directly into the arguments of another. +setTimeout(function(){ + // this code will be called in 5 seconds' time +}, 5000); + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +(function(){ + var temporary = 5; + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables, even after the outer function exits. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope by default, as if they were + // declared with 'var'. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. +} +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s + +/////////////////////////////////// +// 5. More about Objects; Constructors and Prototypes + +// Objects can contain functions. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// When functions attached to an object are called, they can access the object +// they're attached to using the this keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through this, even if it wasn't attached when it was defined. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// We can also specify a context for a function to execute in when we invoke it +// using 'call' or 'apply'. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The 'apply' function is nearly identical, but takes an array for an argument list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of arguments +// and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use +// bind. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Bind can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// When you call a function with the new keyword, a new object is created, and +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property __proto__. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// We mentioned that __proto__ was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there are two ways to +// create a new object with a given prototype. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// the constructor function itself; instead, it's the prototype that new objects +// are given when they're created with that constructor and the new keyword. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Except, they aren't exactly equivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it with this polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## Further Reading + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +guide of all the counter-intuitive parts of the language. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. -- cgit v1.2.3 From 3c0733f45ce2de89888ea3dd2a16401df1a4a6b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:41:16 +0300 Subject: Translate preamble --- ru-ru/javascript-ru.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 7e2c0cca..963805f9 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,16 +9,28 @@ filename: javascript-ru.js lang: ru-ru --- +Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально +предполагалось, что он станет простым вариантом скриптового языка для сайтов, +дополняющий к Java, который в свою очередь использовался бы для более сложных +web-приложений. Но тонкая интегрированность javascript с web-страницей и +встроенная поддержка в браузерах привели к тому, чтобы он стал более +распространен в web-разработке, чем Java. JavaScript was created by Netscape's Brendan Eich in 1995. It was originally intended as a simpler scripting language for websites, complementing the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. +Использование Javascript не ограничивается браузерами. Проект Node.js, +предоставляющий независимую среду выполнения на движке Google Chrome V8 +JavaScript, становится все более популярным. JavaScript isn't just limited to web browsers, though: Node.js, a project that provides a standalone runtime for Google Chrome's V8 JavaScript engine, is becoming more and more popular. +Обратная связь важна и нужна! Вы можете написаться мне +на [@_remedy]() или +[mymail](). Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or [adam@brenecki.id.au](mailto:adam@brenecki.id.au). -- cgit v1.2.3 From 89ac5d6b77e84517e8844d694676f9e25d171538 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:44:21 +0300 Subject: Translate 1st part --- ru-ru/javascript-ru.html.markdown | 56 ++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 13 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 963805f9..aa1d1f3c 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -36,29 +36,43 @@ Feedback would be highly appreciated! You can reach me at [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js +// Комментарии оформляются как в C. +// Обнострочнные комментарии начинаются с двух слешей, // Comments are like C. Single-line comments start with two slashes, +/* а многострочные с слеша и звездочки + и заканчиваются звездочеий и слешом */ /* and multiline comments start with slash-star and end with star-slash */ +// Выражения разделяются с помощью ; // Statements can be terminated by ; doStuff(); +// ... но этого можно и делать, разделители подставляются автоматически +// после перехода на новую строку за исключением особых случаев // ... but they don't have to be, as semicolons are automatically inserted // wherever there's a newline, except in certain cases. doStuff() +// Это может приводить к непредсказуемому результату и поэтому мы будем +// использовать разделители в этом туре. // Because those cases can cause unexpected results, we'll keep on using // semicolons in this guide. /////////////////////////////////// +// 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта +// IEEE 754) +// todo: сформулировать // JavaScript has one number type (which is a 64-bit IEEE 754 double). // Doubles have a 52-bit mantissa, which is enough to store integers // up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 +// В основном базовая арифметика работает предсказуемо // Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 @@ -66,76 +80,92 @@ doStuff() 10 * 2; // = 20 35 / 5; // = 7 +// Включая нецелочисленное деление (todo:уточнить!) // Including uneven division. 5 / 2; // = 2.5 +// Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, +// оно будет приведено к 32-битному целому со знаком. // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 +// (todo:перевести) // Precedence is enforced with parentheses. (1 + 3) * 2; // = 8 +// Есть три особых не реальных числовых значения: // There are three special not-a-real-number values: -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +Infinity; // допустим, результат операции 1/0 +-Infinity; // допустим, результат операции -1/0 +NaN; // допустим, результат операции 0/0 +// Так же есть тип булевых данных. // There's also a boolean type. true; false; +// Строки создаются с помощью ' или ". // Strings are created with ' or ". 'abc'; "Hello, world"; -// Negation uses the ! symbol +// Оператор ! означает отрицание !true; // = false !false; // = true -// Equality is === +// Равество это === 1 === 1; // = true 2 === 1; // = false -// Inequality is !== +// Неравенство это !== 1 !== 1; // = false 2 !== 1; // = true -// More comparisons +// Еще сравнения 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true 2 >= 2; // = true -// Strings are concatenated with + +// Строки складываются с помощью + "Hello " + "world!"; // = "Hello world!" -// and are compared with < and > +// и сравниваются с помощью < и > "a" < "b"; // = true +// Приведение типов выполняется при сравнении с ==... // Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true -// ...unless you use === +// ...в отличие от === "5" === 5; // = false null === undefined; // = false +// Для доступа к конкретному символу строки используйте charAt // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' +// ... или используйте substring для получения подстроки // ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" +// length(длина) - свойство, не используйте () // length is a property, so don't use () "Hello".length; // = 5 +// Есть null и undefined // There's also null and undefined -null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although - // undefined is actually a value itself) +null; // используется что бы указать явно, что значения нет +undefined; // испрользуется чтобы показать, что значения не было установлено + // собственно, undefined так и переводится +// false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении +// в булеву типу становятся false) // false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, +// что "0"==0 // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -- cgit v1.2.3 From 27825265f397087a60e597d5a0a1ae44d180ddc5 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:58:59 +0300 Subject: Translate part 3 --- ru-ru/javascript-ru.html.markdown | 41 +++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index aa1d1f3c..1369d0d7 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,6 +9,8 @@ filename: javascript-ru.js lang: ru-ru --- +todo: привести все названия языка к коректному написанию + Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который в свою очередь использовался бы для более сложных @@ -169,60 +171,83 @@ undefined; // испрользуется чтобы показать, что з // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -// 2. Variables, Arrays and Objects +// 2. Переменные, массивы и объекты +// Переменные объявляются ключевым словом var. Javascript динамически +// типизируемый, так что указывать тип не нужно. +// Присвоение значения описывается с помощью оператора = // Variables are declared with the var keyword. JavaScript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. var someVar = 5; +// если не указать ключевого слова var, ошибки не будет... // if you leave the var keyword off, you won't get an error... someOtherVar = 10; +// ...но переменная будет создана в глобальном контексте, в не области +// видимости, в которой она была объявлена. // ...but your variable will be created in the global scope, not in the scope // you defined it in. +// Переменные объявленные без присвоения значения, содержать undefined // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// Для математических операций над числами есть короткая запись: // There's shorthand for performing math operations on variables: -someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10; // now someVar is 100 +someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь +someVar *= 10; // а теперь -- 100 -// and an even-shorter-hand for adding or subtracting 1 -someVar++; // now someVar is 101 -someVar--; // back to 100 +// еще более короткая запись для добавления и вычитания 1 +someVar++; // теперь someVar равно 101 +someVar--; // обратно к 100 +// Массивы -- упорядоченные списки значений любых типов. // Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; +// Для доступу к элементам массивов используйте квадратные скобки. +// Индексы массивов начинаются с 0 // Their members can be accessed using the square-brackets subscript syntax. // Array indices start at zero. myArray[1]; // = 45 +// Массивы мутабельны(изменяемы) и имеют переменную длину. // Arrays are mutable and of variable length. -myArray.push("World"); +myArray.push("World"); // добавить элемент myArray.length; // = 4 -// Add/Modify at specific index +// Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; +// Объёкты javascript похожи на dictionary или map из других языков +// программирования. Это неупорядочнные коллекции пар ключ-значение. // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; +// Ключи -- это строки, но кавычки не требуются если названия явлюятся +// корректными javascript идентификаторами. Значения могут быть любого типа. // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; +// Доступ к атрибту объекта можно получить с помощью квадратных скобок // Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 +// ... или используя точечную нотацию, при условии что ключ является +// корректным идентификатором // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" +// Объекты мутабельны. В существуюещем объекте можно изменить значние +// или добавить новый атрибут // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; +// При попытке доступа к атрибуту, который до этого не был создан, будет +// возвращен undefined // If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined -- cgit v1.2.3 From 4fefe7ac06d2cfc87c0de263ea87475daa96248e Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:54:49 +0300 Subject: Translate Logic and Control Structures --- ru-ru/javascript-ru.html.markdown | 44 ++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 15 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1369d0d7..c0e4c0fa 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -252,65 +252,79 @@ myObj.myThirdKey = true; myObj.myFourthKey; // = undefined /////////////////////////////////// +// 3. Логика и управляющие структуры // 3. Logic and Control Structures +// +// Синтаксис управляющих структур очень похож на его реализацию в Java. // The syntax for this section is almost identical to Java's. +// if работает так как вы ожидаете. // The if structure works as you'd expect. var count = 1; if (count == 3){ - // evaluated if count is 3 + // выполнится, если значение count равно 3 } else if (count == 4){ - // evaluated if count is 4 + // выполнится, если значение count равно 4 } else { - // evaluated if it's not either 3 or 4 + // выполнится, если значение countне будет равно ни 3 ни 4 } -// As does while. +// Поведение while тоже вполне предсказуемо while (true){ - // An infinite loop! + // Бесконечный цикл } +// Циклы do-while похожи на while, но они всегда выполняются хотябы 1 раз. // Do-while loops are like while loops, except they always run at least once. var input do { input = getInput(); } while (!isValid(input)) +// Цикл for такой же как в C b Java: +// инициализация; условие продолжения; итерация // the for loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ + // выполнится 5 раз // will run 5 times } +// && - логическое и, || - логическое или // && is logical and, || is logical or -if (house.size == "big" && house.colour == "blue"){ +if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } -if (colour == "red" || colour == "blue"){ +if (color == "red" || color == "blue"){ + // если цвет или красный или синий // colour is either red or blue } +// && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case +// иначе помимо правильного case выполнятся и все последующие. // switch statement checks for equality with === // use 'break' after each case // or the cases after the correct one will be executed too. -grade = 'B'; +grade = '4'; // оценка switch (grade) { - case 'A': - console.log("Great job"); + case '5': + console.log("Великолепно"); break; - case 'B': - console.log("OK job"); + case '4': + console.log("Неплохо"); break; - case 'C': - console.log("You can do better"); + case '3': + console.log("Можно и лучше"); break; default: - console.log("Oy vey"); + console.log("Да уж."); break; } -- cgit v1.2.3 From b1ec17dae0827b4c17d18399d4bd666a9e617bc4 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:55:18 +0300 Subject: Fix grammar --- ru-ru/javascript-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index c0e4c0fa..a22055ef 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -237,12 +237,12 @@ var myObj = {myKey: "myValue", "my other key": 4}; myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является -// корректным идентификатором +// корректным идентификатором. // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние -// или добавить новый атрибут +// или добавить новый атрибут. // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; -- cgit v1.2.3 From 44615813763e218e4f1140ff6c9dbcdd6948d858 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 23:21:54 +0300 Subject: Translate 4. Functions, Scope and Closures --- ru-ru/javascript-ru.html.markdown | 50 ++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index a22055ef..b5556f49 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -330,79 +330,117 @@ switch (grade) { /////////////////////////////////// +// 4. Функции, Область видимости и Замыкания // 4. Functions, Scope and Closures +// Функции в JavaScript объявляются с помощью ключевого слова function. // JavaScript functions are declared with the function keyword. function myFunction(thing){ - return thing.toUpperCase(); + return thing.toUpperCase(); // приведение к верхнему регистру } myFunction("foo"); // = "FOO" +// Помните, что значение, которое должно быть возкращено должно начинаться +// на той же строке, где расположено ключевое слово 'return'. В противном случае +// будет возвращено undefined. Такое поведения объясняется автоматической +// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// BSD стиль оформления кода. // Note that the value to be returned must start on the same line as the // 'return' keyword, otherwise you'll always return 'undefined' due to // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction() { - return // <- semicolon automatically inserted here + return // <- разделитель автоматически будет вставлен здесь { thisIsAn: 'object literal' } } myFunction(); // = undefined +// Функции в JavaScript являются объектами, поэтому их можно назначить в +// переменные с разными названиями и передавать в другие функции, как аргументы, +// на пример, при указании обработчика события. // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: function myFunction(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); +// Обратите внимание, что setTimeout не является частью языка, однако он +// доступен в API браузеров и Node.js. // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Объект функции на самом деле не обязательно объявлять с именем - можно +// создать анонимную функцию прямо в аргументах другой функции. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time }, 5000); +// В JavaScript есть области видимости. У функций есть собственные области +// видимости, у других блоков их нет. // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ var i = 5; } -i; // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) + // в языке, создающем области видисти для блоков " +// Это привело к появлению паттерна общего назначения "immediately-executing +// anonymous functions" (сразу выполняющиеся анонимные функции), который +// позволяет предотвратить запись временных переменных в общую облать видимости. // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ var temporary = 5; + // Для доступа к глобальной области видимости можно использовать запись в + // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный + // объект может называться по-разному в небраузерных средах, таких Node.js. // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; })(); -temporary; // raises ReferenceError +temporary; // вызывает исключение ReferenceError permanent; // = 10 +// Одной из сильных сторон JavaScript являются замыкания. Если функция +// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// переменным внешней функции, даже после того, как внешняя функции завершила +// свое выполнение // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; + var prompt = "Привет, " + name + "!"; + // Внутренние фунции помещаются в локальную область видимости, как-будто они + // объявлены с ключевым словом 'var'. // Inner functions are put in the local scope by default, as if they were // declared with 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); + // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds + // завершит свое выполнение сразу и setTimeout вызовет inner позже. + // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной + // prompt, когда будет вызвана. // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has // access to the 'prompt' variable when it is finally called. } -sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением + // "Привет, Вася" по истечении 5 секунд. + /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 6e694a82b2503a2cce524df96c1c59af6d4ecdea Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sun, 2 Nov 2014 01:12:22 +0300 Subject: Translate last chapter --- ru-ru/javascript-ru.html.markdown | 59 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index b5556f49..f0c91278 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -443,8 +443,10 @@ sayHelloInFiveSeconds("Вася"); // откроет модальное окно /////////////////////////////////// +// 5. Немного об Объектах. Конструкторы и Прототипы // 5. More about Objects; Constructors and Prototypes +// Объекты погут содержать функции // Objects can contain functions. var myObj = { myFunc: function(){ @@ -453,6 +455,8 @@ var myObj = { }; myObj.myFunc(); // = "Hello world!" +// Когда функции прикрепленные к объекту вызываются, они могут получить доступ +// к данным объекта, ипользую ключевое слово this. // When functions attached to an object are called, they can access the object // they're attached to using the this keyword. myObj = { @@ -463,12 +467,17 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" +// Содержание this определяется исходя из того, как была вызвана функция, а +// не места её определения. По этой причине наша функция не будет работать вне +// контекста объекта. // What this is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined +// И напротив, функция может быть присвоена объекту и получить доступ к нему +// через this, даже если она не была прикреплена к объекту в момент её создания. // Inversely, a function can be assigned to the object and gain access to it // through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ @@ -477,6 +486,7 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. // We can also specify a context for a function to execute in when we invoke it // using 'call' or 'apply'. @@ -485,10 +495,13 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +// Функция 'apply' очень похожа, но принимает массив со списком аргументов. // The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +// Это может быть удобно, когда работаешь с фунцией принимающей на вход +// последовательность аргументов и нужно передать их в виде массива. // This is useful when working with a function that accepts a sequence of arguments // and you want to pass an array. @@ -496,18 +509,25 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 +// Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите +// зафиксировать контекст для функции, используйте bind. // But, 'call' and 'apply' are only temporary. When we want it to stick, we can use // bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +// bind можно использовать чтобы частично передать аргументы в +// функцию (каррировать). // Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 +// Когда функция вызывается с ключевым словом new, создается новый объект. +// Данный объект становится доступным функции через ключевое слово this. +// Функции спроектированные вызываться таким способом называются конструкторами. // When you call a function with the new keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. @@ -518,10 +538,17 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 +// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ +// к свойству не объявленному в данном объекте, интерпретатор будет искать его +// в прототипе. // Every JavaScript object has a 'prototype'. When you go to access a property // on an object that doesn't exist on the actual object, the interpreter will // look at its prototype. +// Некоторые реализации JS позволяют получить доступ к прототипу с помощью +// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся +// со стандартными способами работы с прототипом несколько позже. // Some JS implementations let you access an object's prototype on the magic // property __proto__. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. @@ -537,10 +564,10 @@ var myPrototype = { myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 - -// This works for functions, too. myObj.myFunc(); // = "hello world!" +// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе +// прототипа и так далее. // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. myPrototype.__proto__ = { @@ -548,21 +575,32 @@ myPrototype.__proto__ = { }; myObj.myBoolean; // = true +// Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если +// изменить прототип, все изменения отразятся во всех его потомках. // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// Как было сказано выше, __proto__ не является стандартом, и нет стандартного +// способа изменить прототип у созданного объекта. Однако, есть два способа +// создать объект с заданным прототипом. // We mentioned that __proto__ was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. +// Первый способ - Object.create, был добавлен в JS относительно недавно, и +// потому не доступен в более ранних реализациях языка. // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 +// Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют +// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// это прототип, который присваевается новым объектам, созданным с этим +// конструктором с помощью ключевого слова new. // The second way, which works anywhere, has to do with constructors. // Constructors have a property called prototype. This is *not* the prototype of // the constructor function itself; instead, it's the prototype that new objects @@ -578,23 +616,30 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 +// У встроенных типов таких, как строки и числа, тоже есть конструкторы, +// создающие эквивалентные объекты-обертки. // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true +// Правда, они не совсем эквивалентны. // Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ + // Этот фрагмент кода не будет выпонен, так как 0 приводится к false // This code won't execute, because 0 is falsy. } if (Number(0)){ + // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. // This code *will* execute, because Number(0) is truthy. } +// Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, +// следовательно вы можете расширить функциональность строки, например. // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ @@ -602,17 +647,23 @@ String.prototype.firstCharacter = function(){ } "abc".firstCharacter(); // = "a" +// Этот факт часто используется для создания полифилов(polyfill) - реализации +// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// использовать в устаревших браузерах. // This fact is often used in "polyfilling", which is implementing newer // features of JavaScript in an older subset of JavaScript, so that they can be // used in older environments such as outdated browsers. +// Например, мы упомянули, что Object.create не доступен во всех версиях +// JavaScript, но мы може создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // не переопределяем если есть Object.create = function(proto){ - // make a temporary constructor with the right prototype + // создаем временный конструктор с заданным прототипом var Constructor = function(){}; Constructor.prototype = proto; + // создаём новый объект с правильным прототипом // then use it to create a new, appropriately-prototyped object return new Constructor(); } -- cgit v1.2.3 From 821880e95f4b61cdb89eebc7d0077a069b43a2a6 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 11:32:51 +0300 Subject: =?UTF-8?q?=C2=A0Add=20Further=20Reading?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ru-ru/javascript-ru.html.markdown | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index f0c91278..1f0cfb3f 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -655,7 +655,7 @@ String.prototype.firstCharacter = function(){ // used in older environments such as outdated browsers. // Например, мы упомянули, что Object.create не доступен во всех версиях -// JavaScript, но мы може создать полифилл. +// JavaScript, но мы можем создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: if (Object.create === undefined){ // не переопределяем если есть @@ -670,30 +670,23 @@ if (Object.create === undefined){ // не переопределяем если } ``` -## Further Reading +## Что еще почитать -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. +[Современный учебник JavaScript](http://learn.javascript.ru/) от Ильи Кантора +является довольно качественным и глубоким учебным материалом, освещающим все +особенности современного языка. Помимо учебника на том же домене можно найти +[перевод спецификации ECMAScript 5.1](http://es5.javascript.ru/) и справочник по +возможностям языка. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) позволяет +довольно быстро изучить основные тонкие места в работе с JS, но фокусируется +только на таких моментах -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. +[Справочник](https://developer.mozilla.org/ru/docs/JavaScript) от MDN +(Mozilla Development Network) содержит информацию о возможностях языка на +английском. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +Название проекта ["Принципы написания консистентного, идиоматического кода на +JavaScript"](https://github.com/rwaldron/idiomatic.js/tree/master/translations/ru_RU) +говорит само за себя. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. - -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. -- cgit v1.2.3 From 958ba0d69e9c4ac21a39d37b61f7dea1b5a155de Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:28:49 +0300 Subject: Remove comments with english + fix some typo --- ru-ru/javascript-ru.html.markdown | 235 +++++++------------------------------- 1 file changed, 44 insertions(+), 191 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1f0cfb3f..abbafc8d 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - - ["--mynamehere--", "http://github.com/--mynamehere--"] + - ["Maxim Koretskiy", "http://github.com/maximkoretskiy"] filename: javascript-ru.js lang: ru-ru --- @@ -13,47 +13,30 @@ todo: привести все названия языка к коректном Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, -дополняющий к Java, который в свою очередь использовался бы для более сложных +дополняющий к Java, который бы в свою очередь использовался для более сложных web-приложений. Но тонкая интегрированность javascript с web-страницей и встроенная поддержка в браузерах привели к тому, чтобы он стал более -распространен в web-разработке, чем Java. -JavaScript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for websites, complementing the use of -Java for more complex web applications, but its tight integration with Web pages -and built-in support in browsers has caused it to become far more common than -Java in web frontends. - -Использование Javascript не ограничивается браузерами. Проект Node.js, +распространен в frontend-разработке, чем Java. + +Использование JavaScript не ограничивается браузерами. Проект Node.js, предоставляющий независимую среду выполнения на движке Google Chrome V8 JavaScript, становится все более популярным. -JavaScript isn't just limited to web browsers, though: Node.js, a project that -provides a standalone runtime for Google Chrome's V8 JavaScript engine, is -becoming more and more popular. Обратная связь важна и нужна! Вы можете написаться мне -на [@_remedy]() или -[mymail](). -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or +на [@adambrenecki](https://twitter.com/adambrenecki) или [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js // Комментарии оформляются как в C. -// Обнострочнные комментарии начинаются с двух слешей, -// Comments are like C. Single-line comments start with two slashes, +// Однострочнные коментарии начинаются с двух слешей, /* а многострочные с слеша и звездочки и заканчиваются звездочеий и слешом */ -/* and multiline comments start with slash-star - and end with star-slash */ // Выражения разделяются с помощью ; -// Statements can be terminated by ; doStuff(); -// ... но этого можно и делать, разделители подставляются автоматически +// ... но этого можно и не делать, разделители подставляются автоматически // после перехода на новую строку за исключением особых случаев -// ... but they don't have to be, as semicolons are automatically inserted -// wherever there's a newline, except in certain cases. doStuff() // Это может приводить к непредсказуемому результату и поэтому мы будем @@ -65,50 +48,41 @@ doStuff() // 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators -// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта -// IEEE 754) -// todo: сформулировать -// JavaScript has one number type (which is a 64-bit IEEE 754 double). -// Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой +// стандарта IEEE 754) +// Числа имеют 52-битную мантиссу, чего достаточно для хранения хранения целых +// чисел до 9✕10¹⁵ приблизительно. 3; // = 3 1.5; // = 1.5 // В основном базовая арифметика работает предсказуемо -// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Включая нецелочисленное деление (todo:уточнить!) -// Including uneven division. +// Включая нецелочисленное деление 5 / 2; // = 2.5 // Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, // оно будет приведено к 32-битному целому со знаком. -// Bitwise operations also work; when you perform a bitwise operation your float -// is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 // (todo:перевести) -// Precedence is enforced with parentheses. +// Приоритет выполнения операций можно менять с помощью скобок. (1 + 3) * 2; // = 8 // Есть три особых не реальных числовых значения: -// There are three special not-a-real-number values: Infinity; // допустим, результат операции 1/0 -Infinity; // допустим, результат операции -1/0 NaN; // допустим, результат операции 0/0 // Так же есть тип булевых данных. -// There's also a boolean type. true; false; // Строки создаются с помощью ' или ". -// Strings are created with ' or ". 'abc'; "Hello, world"; @@ -137,7 +111,6 @@ false; "a" < "b"; // = true // Приведение типов выполняется при сравнении с ==... -// Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true @@ -146,29 +119,23 @@ null == undefined; // = true null === undefined; // = false // Для доступа к конкретному символу строки используйте charAt -// You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' // ... или используйте substring для получения подстроки -// ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" // length(длина) - свойство, не используйте () -// length is a property, so don't use () "Hello".length; // = 5 // Есть null и undefined -// There's also null and undefined null; // используется что бы указать явно, что значения нет undefined; // испрользуется чтобы показать, что значения не было установлено // собственно, undefined так и переводится // false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении // в булеву типу становятся false) -// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. -// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, -// что "0"==0 -// Note that 0 is falsy and "0" is truthy, even though 0 == "0". +// Обратите внимание что 0 приводится к false, а "0" к true, +// не смотря на то, что "0"==0 /////////////////////////////////// // 2. Переменные, массивы и объекты @@ -176,25 +143,18 @@ undefined; // испрользуется чтобы показать, что з // Переменные объявляются ключевым словом var. Javascript динамически // типизируемый, так что указывать тип не нужно. // Присвоение значения описывается с помощью оператора = -// Variables are declared with the var keyword. JavaScript is dynamically typed, -// so you don't need to specify type. Assignment uses a single = character. var someVar = 5; // если не указать ключевого слова var, ошибки не будет... -// if you leave the var keyword off, you won't get an error... someOtherVar = 10; // ...но переменная будет создана в глобальном контексте, в не области // видимости, в которой она была объявлена. -// ...but your variable will be created in the global scope, not in the scope -// you defined it in. // Переменные объявленные без присвоения значения, содержать undefined -// Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// Для математических операций над числами есть короткая запись: -// There's shorthand for performing math operations on variables: +// Для математических операций над переменными есть короткая запись: someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь someVar *= 10; // а теперь -- 100 @@ -203,71 +163,55 @@ someVar++; // теперь someVar равно 101 someVar--; // обратно к 100 // Массивы -- упорядоченные списки значений любых типов. -// Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; // Для доступу к элементам массивов используйте квадратные скобки. // Индексы массивов начинаются с 0 -// Their members can be accessed using the square-brackets subscript syntax. -// Array indices start at zero. myArray[1]; // = 45 // Массивы мутабельны(изменяемы) и имеют переменную длину. -// Arrays are mutable and of variable length. myArray.push("World"); // добавить элемент myArray.length; // = 4 // Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; -// Объёкты javascript похожи на dictionary или map из других языков +// Объекты javascript похожи на dictionary или map из других языков // программирования. Это неупорядочнные коллекции пар ключ-значение. -// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other -// languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; // Ключи -- это строки, но кавычки не требуются если названия явлюятся // корректными javascript идентификаторами. Значения могут быть любого типа. -// Keys are strings, but quotes aren't required if they're a valid -// JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; // Доступ к атрибту объекта можно получить с помощью квадратных скобок -// Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является // корректным идентификатором. -// ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние // или добавить новый атрибут. -// Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; // При попытке доступа к атрибуту, который до этого не был создан, будет // возвращен undefined -// If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Логика и управляющие структуры -// 3. Logic and Control Structures +// 3. Логика и Управляющие структуры -// // Синтаксис управляющих структур очень похож на его реализацию в Java. -// The syntax for this section is almost identical to Java's. // if работает так как вы ожидаете. -// The if structure works as you'd expect. var count = 1; if (count == 3){ // выполнится, если значение count равно 3 } else if (count == 4){ // выполнится, если значение count равно 4 } else { - // выполнится, если значение countне будет равно ни 3 ни 4 + // выполнится, если значение count не будет равно ни 3 ни 4 } // Поведение while тоже вполне предсказуемо @@ -282,36 +226,27 @@ do { input = getInput(); } while (!isValid(input)) -// Цикл for такой же как в C b Java: +// Цикл for такой же как в C и Java: // инициализация; условие продолжения; итерация -// the for loop is the same as C and Java: -// initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // выполнится 5 раз - // will run 5 times } // && - логическое и, || - логическое или -// && is logical and, || is logical or if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } if (color == "red" || color == "blue"){ // если цвет или красный или синий - // colour is either red or blue } // && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; - -// выражение switch проверяет равество с помощью === -// используйте 'break' после каждого case +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case, // иначе помимо правильного case выполнятся и все последующие. -// switch statement checks for equality with === -// use 'break' after each case -// or the cases after the correct one will be executed too. grade = '4'; // оценка switch (grade) { case '5': @@ -331,10 +266,8 @@ switch (grade) { /////////////////////////////////// // 4. Функции, Область видимости и Замыкания -// 4. Functions, Scope and Closures // Функции в JavaScript объявляются с помощью ключевого слова function. -// JavaScript functions are declared with the function keyword. function myFunction(thing){ return thing.toUpperCase(); // приведение к верхнему регистру } @@ -343,7 +276,7 @@ myFunction("foo"); // = "FOO" // Помните, что значение, которое должно быть возкращено должно начинаться // на той же строке, где расположено ключевое слово 'return'. В противном случае // будет возвращено undefined. Такое поведения объясняется автоматической -// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// вставкой разделителей ';'. Помните этот факт, если используете // BSD стиль оформления кода. // Note that the value to be returned must start on the same line as the // 'return' keyword, otherwise you'll always return 'undefined' due to @@ -360,94 +293,66 @@ myFunction(); // = undefined // Функции в JavaScript являются объектами, поэтому их можно назначить в // переменные с разными названиями и передавать в другие функции, как аргументы, // на пример, при указании обработчика события. -// JavaScript functions are first class objects, so they can be reassigned to -// different variable names and passed to other functions as arguments - for -// example, when supplying an event handler: function myFunction(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); // Обратите внимание, что setTimeout не является частью языка, однако он // доступен в API браузеров и Node.js. -// Note: setTimeout isn't part of the JS language, but is provided by browsers -// and Node.js. // Объект функции на самом деле не обязательно объявлять с именем - можно // создать анонимную функцию прямо в аргументах другой функции. -// Function objects don't even have to be declared with a name - you can write -// an anonymous function definition directly into the arguments of another. setTimeout(function(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time }, 5000); // В JavaScript есть области видимости. У функций есть собственные области // видимости, у других блоков их нет. -// JavaScript has function scope; functions get their own scope but other blocks -// do not. if (true){ var i = 5; } -i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) - // в языке, создающем области видисти для блоков " +i; // = 5, а не undefined, как это было бы в языке, создающем + // области видисти для блоков кода // Это привело к появлению паттерна общего назначения "immediately-executing // anonymous functions" (сразу выполняющиеся анонимные функции), который // позволяет предотвратить запись временных переменных в общую облать видимости. -// This has led to a common pattern of "immediately-executing anonymous -// functions", which prevent temporary variables from leaking into the global -// scope. (function(){ var temporary = 5; // Для доступа к глобальной области видимости можно использовать запись в // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный // объект может называться по-разному в небраузерных средах, таких Node.js. - // We can access the global scope by assiging to the 'global object', which - // in a web browser is always 'window'. The global object may have a - // different name in non-browser environments such as Node.js. window.permanent = 10; })(); temporary; // вызывает исключение ReferenceError permanent; // = 10 // Одной из сильных сторон JavaScript являются замыкания. Если функция -// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// объявлена в внутри другой функции, внутренняя функция имеет доступ ко всем // переменным внешней функции, даже после того, как внешняя функции завершила -// свое выполнение -// One of JavaScript's most powerful features is closures. If a function is -// defined inside another function, the inner function has access to all the -// outer function's variables, even after the outer function exits. +// свое выполнение. function sayHelloInFiveSeconds(name){ var prompt = "Привет, " + name + "!"; - // Внутренние фунции помещаются в локальную область видимости, как-будто они - // объявлены с ключевым словом 'var'. - // Inner functions are put in the local scope by default, as if they were - // declared with 'var'. + // Внутренние функции помещаются в локальную область видимости, как-будто + // они объявлены с ключевым словом 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds // завершит свое выполнение сразу и setTimeout вызовет inner позже. - // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // Однако, так как inner "закрыта внутри" или "замкнута в" // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной // prompt, когда будет вызвана. - // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will - // exit immediately, and setTimeout will call inner afterwards. However, - // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the 'prompt' variable when it is finally called. } sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением // "Привет, Вася" по истечении 5 секунд. /////////////////////////////////// -// 5. Немного об Объектах. Конструкторы и Прототипы -// 5. More about Objects; Constructors and Prototypes +// 5. Немного еще об Объектах. Конструкторы и Прототипы -// Объекты погут содержать функции -// Objects can contain functions. +// Объекты могут содержать функции var myObj = { myFunc: function(){ return "Hello world!"; @@ -456,9 +361,7 @@ var myObj = { myObj.myFunc(); // = "Hello world!" // Когда функции прикрепленные к объекту вызываются, они могут получить доступ -// к данным объекта, ипользую ключевое слово this. -// When functions attached to an object are called, they can access the object -// they're attached to using the this keyword. +// к данным объекта, ипользуя ключевое слово this. myObj = { myString: "Hello world!", myFunc: function(){ @@ -470,16 +373,11 @@ myObj.myFunc(); // = "Hello world!" // Содержание this определяется исходя из того, как была вызвана функция, а // не места её определения. По этой причине наша функция не будет работать вне // контекста объекта. -// What this is set to has to do with how the function is called, not where -// it's defined. So, our function doesn't work if it isn't called in the -// context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined // И напротив, функция может быть присвоена объекту и получить доступ к нему // через this, даже если она не была прикреплена к объекту в момент её создания. -// Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); } @@ -487,23 +385,17 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. -// We can also specify a context for a function to execute in when we invoke it -// using 'call' or 'apply'. - var anotherFunc = function(s){ return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // Функция 'apply' очень похожа, но принимает массив со списком аргументов. -// The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" // Это может быть удобно, когда работаешь с фунцией принимающей на вход // последовательность аргументов и нужно передать их в виде массива. -// This is useful when working with a function that accepts a sequence of arguments -// and you want to pass an array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) @@ -511,15 +403,12 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 // Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите // зафиксировать контекст для функции, используйте bind. -// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use -// bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// bind можно использовать чтобы частично передать аргументы в +// bind также можно использовать чтобы частично передать аргументы в // функцию (каррировать). -// Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); @@ -528,9 +417,6 @@ doubler(8); // = 16 // Когда функция вызывается с ключевым словом new, создается новый объект. // Данный объект становится доступным функции через ключевое слово this. // Функции спроектированные вызываться таким способом называются конструкторами. -// When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be -// called like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; @@ -538,20 +424,14 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ -// к свойству не объявленному в данном объекте, интерпретатор будет искать его -// в прототипе. -// Every JavaScript object has a 'prototype'. When you go to access a property -// on an object that doesn't exist on the actual object, the interpreter will -// look at its prototype. +// Любой объект в JavaScript имеет 'прототип'. Когда вы пытаетесь получить +// доступ к свойству не объявленному в данном объекте, интерпретатор будет +// искать его в прототипе. // Некоторые реализации JS позволяют получить доступ к прототипу с помощью -// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// "волшебного" свойства __proto__. До момента пока оно не являются стандартным, // __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся // со стандартными способами работы с прототипом несколько позже. -// Some JS implementations let you access an object's prototype on the magic -// property __proto__. While this is useful for explaining prototypes it's not -// part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!" }; @@ -566,10 +446,8 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 myObj.myFunc(); // = "hello world!" -// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе -// прототипа и так далее. -// Of course, if your property isn't on your prototype, the prototype's -// prototype is searched, and so on. +// Естественно, если в свойства нет в прототипе, поиск будет продолжен в +// прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; @@ -577,34 +455,22 @@ myObj.myBoolean; // = true // Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если // изменить прототип, все изменения отразятся во всех его потомках. -// There's no copying involved here; each object stores a reference to its -// prototype. This means we can alter the prototype and our changes will be -// reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 // Как было сказано выше, __proto__ не является стандартом, и нет стандартного // способа изменить прототип у созданного объекта. Однако, есть два способа // создать объект с заданным прототипом. -// We mentioned that __proto__ was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there are two ways to -// create a new object with a given prototype. // Первый способ - Object.create, был добавлен в JS относительно недавно, и // потому не доступен в более ранних реализациях языка. -// The first is Object.create, which is a recent addition to JS, and therefore -// not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 // Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют -// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// свойство prototype. Это вовсе не прототип функции конструктора, напротив, // это прототип, который присваевается новым объектам, созданным с этим // конструктором с помощью ключевого слова new. -// The second way, which works anywhere, has to do with constructors. -// Constructors have a property called prototype. This is *not* the prototype of -// the constructor function itself; instead, it's the prototype that new objects -// are given when they're created with that constructor and the new keyword. MyConstructor.prototype = { myNumber: 5, getMyNumber: function(){ @@ -618,53 +484,40 @@ myNewObj2.getMyNumber(); // = 6 // У встроенных типов таких, как строки и числа, тоже есть конструкторы, // создающие эквивалентные объекты-обертки. -// Built-in types like strings and numbers also have constructors that create -// equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Правда, они не совсем эквивалентны. -// Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // Этот фрагмент кода не будет выпонен, так как 0 приводится к false - // This code won't execute, because 0 is falsy. } if (Number(0)){ // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. - // This code *will* execute, because Number(0) is truthy. } // Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, // следовательно вы можете расширить функциональность строки, например. -// However, the wrapper objects and the regular builtins share a prototype, so -// you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); } "abc".firstCharacter(); // = "a" // Этот факт часто используется для создания полифилов(polyfill) - реализации -// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// новых возможностей JS в его более старых версиях для того чтобы их можно было // использовать в устаревших браузерах. -// This fact is often used in "polyfilling", which is implementing newer -// features of JavaScript in an older subset of JavaScript, so that they can be -// used in older environments such as outdated browsers. // Например, мы упомянули, что Object.create не доступен во всех версиях // JavaScript, но мы можем создать полифилл. -// For instance, we mentioned that Object.create isn't yet available in all -// implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // не переопределяем если есть +if (Object.create === undefined){ // не переопределяем, если есть Object.create = function(proto){ // создаем временный конструктор с заданным прототипом var Constructor = function(){}; Constructor.prototype = proto; // создаём новый объект с правильным прототипом - // then use it to create a new, appropriately-prototyped object return new Constructor(); } } -- cgit v1.2.3 From c689f9f8218dfa95fe655364301326f8dbd369b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:34:19 +0300 Subject: Remove todos --- ru-ru/javascript-ru.html.markdown | 2 -- 1 file changed, 2 deletions(-) (limited to 'ru-ru') diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index abbafc8d..ad66b501 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,8 +9,6 @@ filename: javascript-ru.js lang: ru-ru --- -todo: привести все названия языка к коректному написанию - Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который бы в свою очередь использовался для более сложных -- cgit v1.2.3