xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript Object-oriented Programming All In One

JavaScript Object-oriented Programming All In One

OOP / 面向对象编程

https://en.wikipedia.org/wiki/Object-oriented_programming

  1. encapsulation 封装

降低复杂性,提高可复用性


  1. abstraction 抽象

降低复杂性,隔离数据变化的产生的影响(副作用)


  1. inheritance 继承

减少冗余代码


  1. polymorphism 多态性 / 泛型

内部实现各种逻辑判断,外部使用简单且一致性;


demo



// 1. Factory Function (return {})
function personFactory (name, age) {
  return {
    name: name,
    age: age,
    getInfo () {
      console.log('name is ', name, ',age is ', age, '.');
    },
  };
}

var eric = personFactory('Eric', 18);
eric.name;
eric.age;
eric.getInfo();

// 2. Constructor Function (this + new): new keyword auto bind this & return {}
function PersonConstructor () {
  this.name = name;
  this.age = age;
  this.getInfo = function () {
    console.log('name is ', this.name, ', age is ', this.age, '.');
  };
}

var xgqfrms = new PersonConstructor('xgqfrms', 23);
xgqfrms.name;
xgqfrms.age;
xgqfrms.getInfo();


// 3. ES6 Class (语法糖🍬)
class Human {
  constructor (uid) {
    this.uid = uid;
  }
}

class Person extends Human {
  constructor (name, age, uid) {
    super(uid ?? Date.now());
    // super(uid ?? new Date().getTime());
    this.name = name;
    this.age = age;
  }
  getId() {
    console.log('\nuid is ', this.uid);
  }
  getInfo() {
    console.log('name is ', this.name, ',age is ', this.age, '.');
  }
  // const uuid = new Date().getTime();
  // static getUUID() {
  //   console.log('uuid is ', uuid);
  // }
}

const person = new Person('super man', 2022);
person.name;
person.age;
person.getInfo();
person.getId();

// Person.getUUID();


编程范式

  1. imperative paradigm 命令式范式

  2. declarative paradigm 声明式范式

https://en.wikipedia.org/wiki/Programming_paradigm

https://en.wikipedia.org/wiki/Comparison_of_multi-paradigm_programming_languages

refs

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming

https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-15 10:03  xgqfrms  阅读(28)  评论(5编辑  收藏  举报