vikramlc / Javascript

0 stars 0 forks source link

Classes and Object-Oriented Programming #11

Open vikramlc opened 4 years ago

vikramlc commented 4 years ago

image

vikramlc commented 4 years ago

instanceof operator:

class Person {
    name = 'Max';
}

const p = new Person();

p
Person {name: "Max"}

typeof p
"object"

p instanceof Person
true

p instanceof Object
true
vikramlc commented 4 years ago

Object descriptors: Object.getOwnPropertyDescriptor():

const object1 = {
  property1: 42
};

const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');

console.log(descriptor1.configurable);
// expected output: true

console.log(descriptor1.value);
// expected output: 42

Object.defineProperties():

const object1 = {};

Object.defineProperties(object1, {
  property1: {
    value: 42,
    writable: true
  },
  property2: {}
});

console.log(object1.property1);
// expected output: 42
vikramlc commented 4 years ago

Class declarations

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Class expressions

// unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle"

// named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle2"

Prototype methods:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100