JS

(OOP)

OOP

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

Abstraction

Абстракции прячут детали и дают нам возможность разговаривать о задачах на высшем, или более абстрактном, уровне.

Encapsulation

Языковой механизм для ограничения доступа к некоторым компонентам объекта.

Inheritance

Является способом повторного использования кода существующих объектов или для определения подтипа существующего объекта или того и другого, в зависимости от поддержки языка программирования.

Polymorphism

Возможность создания переменной, функции или объекта с более чем одной формой.

Abstraction

Encapsulation

Inheritance

Polymorphism

Class

Это способ описания сущности, определяющий состояние и поведение, зависящее от этого состояния, а также правила для взаимодействия с данной сущностью (контракт).

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

Class

Классом в объектно-ориентированной разработке называют шаблон/программный код, предназначенный для создания объектов и методов.

Interface

Набор методов класса, доступных для использования другими классами

this and object

function test() { 
  console.log(this); 
} 

test();
var a = {
   name: 'Вася',
   getA: function() {
      return this;
   }
}

a.name;
a.getA();

let user = a.getA
user();

Context "this"

There are 4 invocation patterns in JS:

// Default Binding
function func() {
    this.a = 1;
    console.log(this.a);
}
func(); 

//Implicit Binding
var a = {
  func: function() {}; // some function
}
a.func();
 
// Explicit Binding
func.apply(thisArg, argArray);

// new Binding
var func = new Func();

Context "this"

One of the most confused mechanisms in JavaScript is the this keyword. It's a special identifier keyword that's automatically defined in the scope of every function

var user = {
  firstName: 'Petya'
};
var admin = {
  firstName: 'Vasya'
};

function getName() {
  return this.firstName;
}

user.a = getName;
user.a(); // returns 'Petya'

Constructor

Constructor is a function that creates and initializes the newly created object according to the template.

function Animal(name) {
  this.name = name;
  this.canWalk = true;
}

var dog = new Animal("dog");

// create obj
// dog = {
//   name: "dog",
//   canWalk: true
// }

Abstraction

var Animal = (function () {
    // constructor
    function Animal (name) {
        // public properties
        this.name = name;
        this.extremities;
        this.isBird;
    }
    // private properties
    var bones;
    // public methods
    Animal.prototype.walk = function () {

    }
    Animal.prototype.breathe = function () {
         
    }
    Animal.prototype.fly = function () {
        
    }
    Animal.prototype.eat = function (food) {
       
    }

    return Animal;
})();

Encapsulation in JS

Objects with identical methods of behavior creates class or object type (javascript). Class retains constructive plan of own objects.

Each object - a member of a class, is an instance of class or object.

const Man = function(name, age) {
    const name = name;
    const age = age;

    this.sayHello = function () {
        console.log('show private variable: ', priv);

        return 'Hello ' + name;
    };
}

const arni = new Man('Arni', 30);

console.log(arni);

Proto and Prototype

Объекты в JavaScript можно организовать в цепочки так, чтобы свойство, не найденное в одном объекте, автоматически искалось бы в другом.

Связующим звеном выступает специальное свойство __proto__

Объект, на который указывает ссылка __proto__, называется «прототипом»

Ссылка __proto__ скрытая и не во всех браузерах доступна.
Мы используем другую ссылку prototype

Class

Базовый синтаксис выглядит так:

class MyClass {
  // методы класса
  constructor() { ... }
  method1() { ... }
  method2() { ... }
  method3() { ... }
  ...
}

Затем используйте вызов new MyClass() для создания нового объекта со всеми перечисленными методами.

Class

Пример

class User {

  constructor(name) {
    this.name = name;
  }

  sayHi() {
    console.log(this.name);
  }

}

// Использование:
let user = new User("Вася");
user.sayHi();

Когда вызывается new User("Иван"):

  1. Создаётся новый объект.
  2. constructor запускается с заданным аргументом и сохраняет его в this.name.

Function Constructor

function User(name) {
  this.name = name;

  this.sayHi = function() {
    console.log( "Меня зовут: " + this.name );
  };
}

Что такое Class?

  1. В JavaScript класс – это разновидность функции.
  2. Классы всегда используют use strict.
  3. В отличие от обычных функций, конструктор класса не может быть вызван без new.

Links

Examples

JS OOP

By Oleg Rovenskyi