A small guide to OOP in js

A small guide to OOP in js

In the guide, I will try to parse the new features of es6 focused on the object-oriented specification.

first,

what are design patterns

A paradigm is an example or model of a transaction in which a computer program is created according to a pattern.

What is Object Orientation

Obviously you realize this is a design pattern, like this one already exists, we have many other design patterns like functional programming and reactive programming.

Features of this mode

What we do in this pattern is to program in a more realistic way, we program with classes, objects, methods, properties, etc., and we integrate terms like abstraction, encapsulation, modularity, privacy, polymorphism, and inheritance.

The problem with javascript is that it's not a very canonical language, why? Since everything in javascript is an object, we can use the well-known one prototypeto solve this problem.

In ES5, we implement the engineering pattern using the following example:

console.log('*** PERSON ***');
function Person (name) {
 this.name = name;
}
// 明确属性和方法
Person.prototype = {
   eyes: 2,
   mouth: 1,
   sleep: function () {
    return 'zzz';
   }
};
// 创建一个叫Nick的人
const p1 = new Person('Nick');

console.log(
  `name: ${p1.name}`,
  `eyes: ${p1.eyes}`,
  `mouth: ${p1.mouth}`,
   p1.sleep()
);
console.log('*** EMPLOYEE ***')
// 如果我们有class属性,我们可以继承person的属性
function Employee (name, salary) {
  this.name = name;
  this.salary = salary;
}
// Prototype 继承
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee; // Set his own constructor
// 现在可以做相同的事情了
// 创建一个employee
const em1 = new Employee('John', 3000);

console.log(
  `name: ${em1.name}`,
  `salary: ${em1.salary} USD`,
  `eyes: ${em1.eyes}`,
  `mouth: ${em1.mouth}`,
   em1.sleep()
);

Now using ES6, there is a simple way to do the above, but keep in mind that this is just syntactic sugar:

class Person {
  constructor (name) {
    this.name = name;
    this.eyes = 2;
    this.mouth = 1;
  }
  sleep () {
    return 'zzz';
  }
}
class Employee extends Person {
  constructor (name, salary) {
    super(name);
    this.salary = salary;
  }
}
const p1 = new Person('Nick');
console.log(
  `name: ${p1.name}`,
  `eyes: ${p1.eyes}`,
  `mouth: ${p1.mouth}`,
   p1.sleep()
);
const em1 = new Employee('John', 3000);
console.log(
  `name: ${em1.name}`,
  `salary: ${em1.salary} USD`,
  `eyes: ${em1.eyes}`,
  `mouth: ${em1.mouth}`,
   em1.sleep()
);

In this case, by extendskeyword we just say: Well, I want to inherit Personthe properties of the class. But behind the scenes, it's the same thing we're doing with the prototype in the es5 example.

static method

class Dog {
  static whatIs() {
   return 'A dog is a beatiful animal';
  }
}
// 因此,我们通过静态方法,不用实例化一个新的对象就可以访问方法
console.log( Dog.whatIs() );

private property

javascript doesn't have private properties like java and c# do. Importantly, in JavaScript we have a convention for "private" values, which is to use an underscore before the word :

class Person {
 constructor (name, phone) { 
   this.name = name;
   this._phone = phone;
 }
}
const p1 = new Person('John', 544342212);
// 实际上 'phone' 不是一个私有属性,因为我们可以这样使用:
console.log(p1._phone);

However in ES6 we have an object called WeakMap which allows us to create private properties. Let's take a look:

// 因为它是保留字,所以不要使用private作为变量名称
const secret = new WeakMap();
class Person {
  constructor (name, phone) {
    this.name = name;
    secret.set(this, {_phonenumber: phone});
  }
}
const p1 = new Person('John', 544342212);
// 现在_phonenumber是一个私有属性
console.log(p1. _phonenumber); // Print's undefined

Getters 和 Setters

When we have private methods it is common to create a public method that returns a private value, so we have to return a value and define a new value.

const secret = new WeakMap();
class Person {
  constructor (name, phone) {
    this.name = name;
    secret.set(this, {_phonenumber: phone
  }
  get phoneNumber() {
    return secret.get(this)._phonenumber;
  }
  set phoneNumber(newNumber) {
    secret.get(this)._phonenumber = newNumber;
  }
}
const p1 = new Person('John', 544342212);
const p2 = new Person('Tom', 111111);
// 通过getter获取手机号
console.log(p1.phoneNumber); // Print's the number
// 设置新的手机号
p1.phoneNumber = 432232323;
p1.phoneNumber = 222222;
console.log(p1.phoneNumber, p2.phoneNumber); // 获得新的手机号

polymorphism

During execution, an object references the events of its class or any subclasses. Subclasses may redefine a method.

class Person {
  constructor(name) {
    this.name = name;
  }
  me() {
    return `My name is ${this.name}`;
  }
}
const axel = new Person('Axel');
console.log(axel.me());
  // ->  'My name is Axel'
class Employee extends Person {
  constructor (name, salary) {
    super(name);
    this.salary = salary;
  }
  me() {
    return `My name is ${this.name} and my salary is ${this.salary}`;
  } 
}
const nick = new Employee('Nick', 3000);
console.log(nick.me());
  // ->  'My name is Nick and my salary is 3000'

some concepts

  • class: Create a new class or model.
  • constructor: The method to initialize the object when instantiating the class.
  • extends: used to set inheritance
  • super: Sets the method that invokes the parent's inherited properties. supe must be on the first line of the constructor.
  • get: A method to get a value.
  • set: A method to redefine a value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325056063&siteId=291194637