JavaScript Object-oriented Programming All In One
JavaScript Object-oriented Programming All In One
OOP / 面向对象编程
https://en.wikipedia.org/wiki/Object-oriented_programming
- encapsulation 封装
降低复杂性,提高可复用性
- abstraction 抽象
降低复杂性,隔离数据变化的产生的影响(副作用)
- inheritance 继承
减少冗余代码
- 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();
编程范式
-
imperative paradigm 命令式范式
-
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, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16007231.html
未经授权禁止转载,违者必究!