Skip to content

Instantly share code, notes, and snippets.

@dyukovlad
Forked from DawnPaladin/js-reference.js
Last active February 13, 2018 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyukovlad/62eeda1418c188c22645a5d1e6bda221 to your computer and use it in GitHub Desktop.
Save dyukovlad/62eeda1418c188c22645a5d1e6bda221 to your computer and use it in GitHub Desktop.
JavaScript reference guide
OBJECTS
=====
// Существует два способа создания объектов: буквенное обозначение и обозначение конструкции.
//
// Буквенная нотация использует фигурные скобки:
var james = {
job: "programmer",
married: false,
greet: function() {
console.log("Hello!");
}
};
// Обозначение конструктора создает конструктор, который вы можете использовать для извлечения множества похожих объектов, эффективно превращая его в класс. Функции в JavaScript всегда являются объектами, что означает, что они имеют свой собственный домен, могут иметь свои собственные свойства, дети и т. Д.
function Person(job, married) {
this.job = job;
this.married = married;
}
// Then you create an object using the "new" keyword:
// Затем вы создаете объект, используя ключевое слово «новое»:
var gabby = new Person("student", true);
// A method is a function that's built into an object:
// Метод - это функция, встроенная в объект:
function Person(job, married) {
this.speak = function() {
console.log("Hello!");
}
}
// Or, using literal notation:
// Или, используя буквенную нотацию:
var james = {
speak: function(speech) {
console.log("Hello, I am feeling " + speech);
}
};
// OBJECT PROPERTIES
// Свойства объекта
// Normally you access object properties using dot notation (someObj.propName). But sometimes it's useful to treat the property name as a variable. You can do that by accessing the object as if it were an array.
// Обычно вы получаете доступ к свойствам объекта с использованием точечной нотации (someObj.propName). Но иногда полезно рассматривать имя свойства как переменную. Вы можете сделать это, обратившись к объекту так, как если бы это был массив.
var someObj = {propName: someValue} //object created
var myProperty = "propName";
someObj[myProperty] //These two lines
someObj["propName"] //do exactly the same thing.
// This comes into play when using "for-in" loops:
// Это происходит при использовании циклов for-in:
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for(var i in nyc) {
console.log(i); // Prints the name of each of nyc's properties
console.log(nyc[i]); // Prints the value of each of nyc's properties
}
// You can check whether a property exists with hasOwnProperty
// Вы можете проверить, существует ли свойство с hasOwnProperty
console.log(nyc.hasOwnProperty('mayor')) // prints "true", because nyc has a mayor
// You can check what type a property is (boolean, string, number, function, etc.) with typeof
// Вы можете проверить, какой тип имеет свойство (логическое значение, строка, число, функция и т. Д.) С помощью typeof
console.log(typeof nyc[mayor]) // prints "string"
CLASSES
=====
// Classes are just objects with children.
// Классы - это просто объекты с детьми.
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs
}
// creates a class named Animal with two properties (name and numLegs) which can be passed in as parameters.
// создает класс с именем Animal с двумя свойствами (name и numLegs), которые могут быть переданы как параметры.
// Generally you'll want to define the class as much as you can up-front, but if you need to modify it afterwards, you can do so by making changes to the prototype:
// Как правило, вы захотите определить класс столько, сколько сможете, но если вам нужно его потом изменить, вы можете сделать это, внеся изменения в прототип:
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
// adds a method to the Animal class called sayName.
// добавляет метод в класс Animal с именем sayName.
// This is also how you set up inheritance.
// Это также то, как вы настраиваете наследование.
Penguin.prototype = new Animal();
// changes Penguin into a subclass of Animal.
//изменяет Penguin в подкласс Animal.
// To make an object that's a member of a class:
// Чтобы создать объект, являющийся членом класса:
var george = new Penguin();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment