JS 

OOP 

Parengė: Martynas Kašelionis

From zero to hero

JS apibrėžimas

JavaScript (JS) is a lightweight interpreted or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

Objektas

 

Objektas susijusių duomenų, veiksmų ir kodo rinkinys.

 

Tai pat gali būti apibrėžiamas, kaip ankščiau paminėtų dalykų kolekcija realaus dalyko, kuris yra modeliuojamas.

 

Projektuojant aplikacijas, objektas dažnai vadinamas modeliu.

Objektas

First class function

const foo = function() {
   console.log("foobar");
}
// Invoke it using the variable
foo();

Prototype based

Prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object.

In simple words: this type of style allows the creation of an object without first defining its class.

 

Priminimas

 

 

(beveik) Viskas Js yra objektai.

 

Objektas

var person = {
  name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
  bio: function() {
    alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old.
 He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
  },
  greeting: function() {
    alert('Hi! I\'m ' + this.name[0] + '.');
  }
};

Objektas. Get

person.name
person.name[0]
person.age
person.interests[1]
person.bio()
person.greeting()

Aukščiau pateiktame pavyzdyje namespace yra person

Sub namespace naudojimas

name : {
  first: 'Bob',
  last: 'Smith'
}
person.name.first
person.name.last

Bracket notation

person.age
person.name.first
person['age']
person['name']['first']

Set

person.age = 45;
person['name']['last'] = 'Cratchit';
person.age
person['name']['last']

This

var person1 = {
  name: 'Chris',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

var person2 = {
  name: 'Brian',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

Nuoroda į objektą

This

var person1 = {
  name: 'Chris',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

var person2 = {
  name: 'Brian',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

Nuoroda į objektą

Konstruktorius

JavaScript naudoja specialias funkcijas, kurios yra konstruktoriai. 

Konstruktorius naudojamas inicijuojamo objekto apibrėžimui.

 

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + obj.name + '.');
  };
  return obj;
}
var salva = createNewPerson('Salva');
salva.name;
salva.greeting();

Konstruktorius

Dar vienas pavyzdys, kodėl reikalingas this​

function Person(name) {
  this.name = name;
  this.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
}

Konstruktoriaus funkcijos pavadinimas pradedamas iš didžiosios raidės, kad būtų lengviau išskiriamas iiš kitų funkcijų.

Konstruktoriaus funkcija yra class analogas, kai nėra naudojama ES6

Konstruktorius

Naujo objekto iniciavimas

Konstruktorius

var person1 = new Person('Bob');
var person2 = new Person('Sarah');

Naujo objekto iniciavimas

person1.name
person1.greeting()
person2.name
person2.greeting()

Kiti iniciavimo būdai

var person1 = new Object();

Galima naudoti Object() konstruktorių

person1.name = 'Chris';
person1['age'] = 38;
person1.greeting = function() {
  alert('Hi! I\'m ' + this.name + '.');
};

Jis sukuria naują objektą, kuris priskiriamas person1

Objektų prototipai

JavaScript apibrėžiama, kaip prototipais paremta kalba.

Objektai gali turėti objekto prototipą, kuris veikia kaip šablono objektas, kurį jis paveldi iš metodų ir savybių.  

Objekto prototipas, gali turėti prototipo objektą, kuris paveldi savybes, bei metodus. Tai vadinama prototipo grandine, tai paaiškina, kodėl skirtingi objektai turi ypatybes ir metodus, kurie apibrėžti kitame objekte.

Objektų prototipai

JavaScript programavimo kalboje ryšys tarp iniciuoto objekto  ir jo prototipo  sukuriamas _proto_ ypatybės konstruktoriuje  dėka 

Objektų prototipai

function Person(first, last, age, gender, interests) {
  
  // property and method definitions
  this.first = first;
  this.last = last;
//...
}
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);

Objektų prototipai

Objektų prototipai

function Person(first, last, age, gender, interests) {

  // property and method definitions

}

var person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing']);

Person.prototype.farewell = function() {
  alert(this.name.first + ' has left the building. Bye for now!');
};

Objektų prototipai

Paveldėjimas

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};
function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

ECMAScript 2015 klasės

EcmaScript 2015 atsirado klasės sintaksė, kuri leidžia rašyti pernaudojamas klases, kurių pagalba turime tvarkingesnį ir aiškesnį kodą, kaip ir kitose programavimo kalbose (JAVA, PHP)

ECMAScript 2015 klasės

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}

Paveldėjimas

class Teacher extends Person {
  constructor(subject, grade) {
    this.subject = subject;
    this.grade = grade;
  }
}   // gauname klaidą nes reikia naudoti super operatorių nurodant paveldimo konstruktoriaus parametrus


class Teacher extends Person {
  constructor(first, last, subject, grade) {
    super(first, last);
    this.subject = subject;
    this.grade = grade;
  }
}


Geteriai ir seteriai

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);
    // subject and grade are specific to Teacher
    this._subject = subject;
    this.grade = grade;
  }

  get subject() {
    return this._subject;
  }

  set subject(newSubject) {
    this._subject = newSubject;
  }
}

Geteriai ir seteriai

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);
    // subject and grade are specific to Teacher
    this._subject = subject;
    this.grade = grade;
  }

  get subject() {
    return this._subject;
  }

  set subject(newSubject) {
    this._subject = newSubject;
  }
}

Detalus objektinis modelis

Tips: this ir that

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});

JS OOP

By Martynas Kašelionis