JS面向对象补充
本文章来源于王红元老师(coderwhy)的 JS高级课程
附上链接:https://ke.qq.com/course/3619571
谁能拒绝一个*100%好评还加课的老师呢
认识class定义类
-
我们会发现,按照前面的构造函数形式创建类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解。
- 在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
- 但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
- 所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系;
-
那么,如何使用class来定义一个类呢?
- 可以使用两种方式来声明类:类声明和类表达式;
class Person { } var Student = class { }
类和构造函数的异同
-
我们来研究一下类的一些特性:
- 你会发现它和我们的构造函数的特性其实是一致的;
var p = new Person console.log(Person) // [class Person] console.log(Person.prototype) // {} console.log(Person.prototype.constructor) // [class Person] console.log(p.__proto__ === Person.prototype) // true console.log(typeof Person) // function
类的构造函数
- 如果我们希望在创建对象的时候给类传递一些参数,这个时候应该如何做呢?
- 每个类都可以有一个自己的构造函数(方法),这个方法的名称是固定的constructor;
- 当我们通过new操作符,操作一个类的时候会调用这个类的构造函数constructor;
- 每个类只能有一个构造函数,如果包含多个构造函数,那么会抛出异常;
- 当我们通过new关键字操作类的时候,会调用这个constructor函数,并且执行如下操作:
- 在内存中创建一个新的对象(空对象);
- 这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性;
- 构造函数内部的this,会指向创建出来的新对象;
- 执行构造函数的内部代码(函数体代码);
- 如果构造函数没有返回非空对象,则返回创建出来的新对象;
类的实例方法
- 在上面我们定义的属性都是直接放到了this上,也就意味着它是放到了创建出来的新对象中:
- 在前面我们说过对于实例的方法,我们是希望放到原型上的,这样可以被多个实例来共享;
- 这个时候我们可以直接在类中定义;
类的访问器方法
- 我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的,那么类也是可以的:
类的静态方法
- 静态方法通常用于定义直接使用类来执行的方法,不需要有类的实例,使用static关键字来定义:
var names = ["abc", "cba", "nba"]
class Person {
constructor(name, age) {
this.name = name
this.age = age
this._address = "广州市"
}
// 普通的实例方法
// 创建出来的对象进行访问
// var p = new Person()
// p.eating()
eating() {
console.log(this.name + " eating~")
}
running() {
console.log(this.name + " running~")
}
// 类的访问器方法
get address() {
console.log("拦截访问操作")
return this._address
}
set address(newAddress) {
console.log("拦截设置操作")
this._address = newAddress
}
// 类的静态方法(类方法)
// Person.createPerson()
static randomPerson() {
var nameIndex = Math.floor(Math.random() * names.length)
var name = names[nameIndex]
var age = Math.floor(Math.random() * 100)
return new Person(name, age)
}
}
var p = new Person("why", 18)
p.eating()
p.running()
console.log(p.address)
p.address = "北京市"
console.log(p.address)
// console.log(Object.getOwnPropertyDescriptors(Person.prototype))
for (var i = 0; i < 50; i++) {
console.log(Person.randomPerson())
}
ES6类的继承 - extends
-
前面我们花了很大的篇幅讨论了在ES5中实现继承的方案,虽然最终实现了相对满意的继承机制,但是过程却依然 是非常繁琐的。
- 在ES6中新增了使用extends关键字,可以方便的帮助我们实现继承:
class Person { } class Student extends Person { }
super关键字
-
我们会发现在上面的代码中我使用了一个super关键字,这个super关键字有不同的使用方式:
- 注意:在子(派生)类的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数!
- super的使用位置有三个:子类的构造函数、实例方法、静态方法;
// 调用 父对象/父类 的构造函数 super([arguments]) // 调用 父对象/父类 上的方法 super.functionOnParent([arguments])
如何使用babel进行es6转es5代码
- 打开babel官网babel.io
- 点击上方Try is out
- 配置,选择targets,修改默认配置信息
- 选择 prettity 对转换后的代码进行美化
创建对象源码阅读
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
eating() {
console.log(this.name + " eating~")
}
}
// babel转换
"use strict"; // 严格模式
function _classCallCheck(instance, Constructor) {
// 2:此方法会检查this的实例是不是通过new创建出来的
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) { // 原型 数组
// 遍历数组
for (var i = 0; i < props.length; i++) {
// 取到其中每个属性
var descriptor = props[i];
// 设置可枚举属性
descriptor.enumerable = descriptor.enumerable || false;
// 设置可配置属性
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
// 将取到的key加入到原型上面 再加上descriptor
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
// 如果protoProps有值则调用_defineProperties函数传入 原型和数组
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
// 如果还有静态方法的话就会直接把静态方法定义到Constructor上去
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var Person = /*#__PURE__*/ (
function() {
// 立即执行函数,前方Person所接受的函数就是下方返回的Person函数
// 防止在全局作用域下变量名直接的冲突所以使用一个函数作用域包裹
// /*#__PURE__*/ 标记为纯函数
// webpack 压缩 tree-shaking(摇树)
// 这个函数没副作用
function Person(name, age) {
// 1:这段代码的功能是防止使用普通函数方式去调用Person
_classCallCheck(this, Person);
this.name = name;
this.age = age;
}
_createClass(Person, [{
key: "eating",
value: function eating() {
console.log(this.name + " eating~");
}
}]);
return Person;
}
)();
继承源码阅读
// class Person {
// constructor(name, age) {
// this.name = name
// this.age = age
// }
// running() {
// console.log(this.name + " running~")
// }
// static staticMethod() {
// }
// }
// class Student extends Person {
// constructor(name, age, sno) {
// super(name, age)
// this.sno = sno
// }
// studying() {
// console.log(this.name + " studying~")
// }
// }
// babel转换后的代码
"use strict";
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj &&
typeof Symbol === "function" &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? "symbol"
: typeof obj;
};
}
return _typeof(obj);
}
// 实现继承
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: { value: subClass, writable: true, configurable: true }
});
// 目的静态方法的继承
// Student.__proto__ = Person
if (superClass) _setPrototypeOf(subClass, superClass);
}
// o: Student
// p: Person
// 静态方法的继承
function _setPrototypeOf(o, p) {
_setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError(
"Derived constructors may only return object or undefined"
);
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var Person = /*#__PURE__*/ (function () {
function Person(name, age) {
_classCallCheck(this, Person);
this.name = name;
this.age = age;
}
_createClass(Person, [
{
key: "running",
value: function running() {
console.log(this.name + " running~");
}
}
]);
return Person;
})();
var Student = /*#__PURE__*/ (function (_Person) {
// 实现之前的寄生式继承的方法(静态方法的继承)
_inherits(Student, _Person);
var _super = _createSuper(Student);
function Student(name, age, sno) {
var _this;
_classCallCheck(this, Student);
// Person不能被当成一个函数去调用
// Person.call(this, name, age)
debugger;
// 创建出来的对象 {name: , age: }
_this = _super.call(this, name, age);
_this.sno = sno;
// {name: , age:, sno: }
return _this;
}
_createClass(Student, [
{
key: "studying",
value: function studying() {
console.log(this.name + " studying~");
}
}
]);
return Student;
})(Person);
var stu = new Student()
// Super: Person
// arguments: ["why", 18]
// NewTarget: Student
// 会通过Super创建出来一个实例, 但是这个实例的原型constructor指向的是NewTarget
// 会通过Person创建出来一个实例, 但是这个实例的原型constructor指向的Person
Reflect.construct(Super, arguments, NewTarget);
阅读源码
- 阅读源码大家遇到的最大的问题:
- 一定不要浮躁
- 看到后面忘记前面的东西
- Bookmarks的打标签的工具:command(ctrl) + alt + k
- 读一个函数的时候忘记传进来是什么?
- 读完一个函数还是不知道它要干嘛
- debugger
继承内置类
- 我们也可以让我们的类继承自内置类,比如Array:
class MjArray extends Array {
firstItem() {
return this[0]
}
lastItem() {
return this[this.length-1]
}
}
var arr = new MjArray(1, 2, 3)
console.log(arr.firstItem())
console.log(arr.lastItem())
类的混入mixin
-
JavaScript的类只支持单继承:也就是只能有一个父类
-
那么在开发中我们我们需要在一个类中添加更多相似的功能时,应该如何来做呢?
-
这个时候我们可以使用混入(mixin);
class Person {
}
function mixinRunner(BaseClass) {
class NewClass extends BaseClass {
running() {
console.log("running~")
}
}
return NewClass
}
function mixinEater(BaseClass) {
return class extends BaseClass {
eating() {
console.log("eating~")
}
}
}
// 在JS中类只能有一个父类: 单继承
class Student extends Person {
}
var NewStudent = mixinEater(mixinRunner(Student))
var ns = new NewStudent()
ns.running()
ns.eating()
在react中的高阶组件
JavaScript中的多态
- 面向对象的三大特性:封装、继承、多态。
- 前面两个我们都已经详细解析过了,接下来我们讨论一下JavaScript的多态。
- JavaScript有多态吗?
- 维基百科对多态的定义:多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口,或使用一 个单一的符号来表示多个不同的类型。
- 非常的抽象,个人的总结:不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。
- 那么从上面的定义来看,JavaScript是一定存在多态的。
function sum(a,b){
console.log(a + b)
}
sum(10, 20)
sum("abc","cba")
字面量的增强
- ES6中对 对象字面量 进行了增强,称之为 Enhanced object literals(增强对象字面量)。
- 字面量的增强主要包括下面几部分:
- 属性的简写:Property Shorthand
- 方法的简写:Method Shorthand
- 计算属性名:Computed Property Names
var name = "why"
var age = 18
var obj = {
// 1.property shorthand(属性的简写)
name,
age,
// 2.method shorthand(方法的简写)
foo: function() {
console.log(this)
},
bar() {
console.log(this)
},
baz: () => {
console.log(this)
},
// 3.computed property name(计算属性名)
[name + 123]: 'hehehehe'
}
obj.baz()
obj.bar()
obj.foo()
// obj[name + 123] = "hahaha"
console.log(obj)
解构Destructuring
- ES6中新增了一个从数组或对象中方便获取数据的方法,称之为解构Destructuring。
- 我们可以划分为:数组的解构和对象的解构。
- 数组的解构:
- 基本解构过程
- 顺序解构
- 解构出数组
- 默认值
- 对象的解构:
- 基本解构过程
- 任意顺序
- 重命名
- 默认值
解构的应用场景
- 解构目前在开发中使用是非常多的:
- 比如在开发中拿到一个变量时,自动对其进行解构使用;
- 比如对函数的参数进行解构;
- 数组的解构
var names = ["abc", "cba", "nba"]
// var item1 = names[0]
// var item2 = names[1]
// var item3 = names[2]
// 对数组的解构: []
var [item1, item2, item3] = names
console.log(item1, item2, item3)
// 解构后面的元素
var [, , itemz] = names
console.log(itemz)
// 解构出一个元素,后面的元素放到一个新数组中
var [itemx, ...newNames] = names
console.log(itemx, newNames)
// 解构的默认值
var [itema, itemb, itemc, itemd = "aaa"] = names
console.log(itemd)
- 对象的解构
var obj = {
name: "why",
age: 18,
height: 1.88
}
// 对象的解构: {}
var { name, age, height } = obj
console.log(name, age, height)
var { age } = obj
console.log(age)
var { name: newName } = obj
console.log(newName)
var { address: newAddress = "广州市" } = obj
console.log(newAddress)
function foo(info) {
console.log(info.name, info.age)
}
foo(obj)
function bar({name, age}) {
console.log(name, age)
}
bar(obj)
le.log(itemz)
// 解构出一个元素,后面的元素放到一个新数组中
var [itemx, …newNames] = names
console.log(itemx, newNames)
// 解构的默认值
var [itema, itemb, itemc, itemd = “aaa”] = names
console.log(itemd)
- 对象的解构
```js
var obj = {
name: "why",
age: 18,
height: 1.88
}
// 对象的解构: {}
var { name, age, height } = obj
console.log(name, age, height)
var { age } = obj
console.log(age)
var { name: newName } = obj
console.log(newName)
var { address: newAddress = "广州市" } = obj
console.log(newAddress)
function foo(info) {
console.log(info.name, info.age)
}
foo(obj)
function bar({name, age}) {
console.log(name, age)
}
bar(obj)