JS面向对象补充

本文章来源于王红元老师(coderwhy)的 JS高级课程
附上链接:https://ke.qq.com/course/3619571
谁能拒绝一个*100%好评还加课的老师呢

目录

  • JS面向对象补充
    • 认识class定义类
    • 类和构造函数的异同
    • 类的构造函数
    • 类的实例方法
    • 类的访问器方法
    • 类的静态方法
    • ES6类的继承 - extends
    • super关键字
    • 如何使用babel进行es6转es5代码
    • 创建对象源码阅读
    • 继承源码阅读
    • 阅读源码
    • 继承内置类
    • 类的混入mixin
    • 在react中的高阶组件
    • JavaScript中的多态
    • 字面量的增强
    • 解构Destructuring
    • 解构的应用场景

认识class定义类

  • 我们会发现,按照前面的构造函数形式创建类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解。

    • 在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
    • 但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
    • 所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系;
  • 那么,如何使用class来定义一个类呢?

    • 可以使用两种方式来声明类:类声明和类表达式;
    class Person {}var Student = class {}
    

类和构造函数的异同

  • 我们来研究一下类的一些特性:

    • 你会发现它和我们的构造函数的特性其实是一致的;
    var p = new Personconsole.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函数,并且执行如下操作:
    1. 在内存中创建一个新的对象(空对象);
    2. 这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性;
    3. 构造函数内部的this,会指向创建出来的新对象;
    4. 执行构造函数的内部代码(函数体代码);
    5. 如果构造函数没有返回非空对象,则返回创建出来的新对象;

类的实例方法

  • 在上面我们定义的属性都是直接放到了this上,也就意味着它是放到了创建出来的新对象中:

    • 在前面我们说过对于实例的方法,我们是希望放到原型上的,这样可以被多个实例来共享;
    • 这个时候我们可以直接在类中定义;

类的访问器方法

  • 我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的,那么类也是可以的:

类的静态方法

  • 静态方法通常用于定义直接使用类来执行的方法,不需要有类的实例,使用static关键字来定义:
var names = ["abc", "cba", "nba"]class Person {constructor(name, age) {this.name = namethis.age = agethis._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代码

  1. 打开babel官网babel.io
  2. 点击上方Try is out
  3. 配置,选择targets,修改默认配置信息
  4. 选择 prettity 对转换后的代码进行美化

创建对象源码阅读

class Person {constructor(name, age) {this.name = namethis.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加入到原型上面 再加上descriptorObject.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__ = Personif (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);

阅读源码

  • 阅读源码大家遇到的最大的问题:

    1. 一定不要浮躁
    2. 看到后面忘记前面的东西
      • Bookmarks的打标签的工具:command(ctrl) + alt + k
      • 读一个函数的时候忘记传进来是什么?
    3. 读完一个函数还是不知道它要干嘛
    4. 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 = 18var 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)

9.JS面向对象补充相关推荐

  1. JavaScript – 6.JS面向对象基础(*) + 7.Array对象 + 8.JS中的Dictionary + 9.数组、for及其他...

    6.JS面向对象基础(*) 7.Array对象 7.1 练习:求一个数组中的最大值.定义成函数. 7.2 练习:将一个字符串数组输出为|分割的形式,比如"刘在石|金钟国|李光洙|HAHA|宋 ...

  2. JS面向对象一:MVC的面向对象封装

    JS面向对象一:MVC的面向对象封装 MDNjavascript面向对象 面向对象(Object-Oriented) 面向对象里面向的意思是以...为主,面向对象编程既以对象为主的编程. 面向对象的一 ...

  3. java实现选项卡定时轮播_原生js面向对象编程-选项卡(自动轮播)

    原生js面向对象编程-选项卡(自动轮播) }#div1 input{color:#fff;width:100px;height:40px;background:darkseagreen;border: ...

  4. js面向对象程序设置——创建对象

    <script type="text/javascript">              //工厂方式         //1.原始方式         /* var ...

  5. 简单粗暴地理解js原型链–js面向对象编程

    简单粗暴地理解js原型链–js面向对象编程 作者:茄果 链接:http://www.cnblogs.com/qieguo/archive/2016/05/03/5451626.html 原型链理解起来 ...

  6. 对js面向对象的理解

    转自:http://www.cnblogs.com/jingwhale/p/4678656.html js面向对象理解 ECMAScript 有两种开发模式:1.函数式(过程化),2.面向对象(OOP ...

  7. JS面向对象的程序设计之继承-继承的实现-借用构造函数

    JS面向对象的程序设计之继承-继承的实现-借用构造函数 前言:最近在细读Javascript高级程序设计,对于我而言,中文版,书中很多地方翻译的差强人意,所以用自己所理解的,尝试解读下.如有纰漏或错误 ...

  8. js面向对象与PHP面向对象总结

    js面向对象: 1.什么是对象? 对象:任何实体都是对象,拥有属性和方法两大特征 属性:描述事物的特点: 方法:实物拥有的行为: 2.在JS里 Person.name="zhang" ...

  9. ES6学习笔记(三):教你用js面向对象思维来实现 tab栏增删改查功能

    前两篇文章主要介绍了类和对象.类的继承,如果想了解更多理论请查阅<ES6学习笔记(一):轻松搞懂面向对象编程.类和对象>.<ES6学习笔记(二):教你玩转类的继承和类的对象>, ...

最新文章

  1. 2021年大数据常用语言Scala(三十一):scala面向对象 特质(trait)
  2. 苹果8a1660是什么版本_iOS 13频繁“翻车”,果粉们面对苹果将情何以堪
  3. ArcGIS百米网格自动生成
  4. openssl之EVP系列之1---算法封装
  5. 07-01-安装-Exchange Server 2019 on Win 2019 Core
  6. 用函数式编程,从0开发3D引擎和编辑器(三):初步需求分析
  7. 针对C++和Delphi的LiveBindings一瞥
  8. 微型计算机突然断电什么信息全部都是,微型计算机的硬件组成阶段作业(函授2014春).doc...
  9. java sdk下载_Java Sdk下载 | 保利威帮助中心
  10. bash初识,shell的基础语法及基本特性
  11. Chorme Error 312 (net::ERR_UNSAFE_PORT) | Chorme 不信任端口
  12. php android 乱码,如何解决android php 中文乱码问题
  13. 三周第二次课(4月3日)
  14. 适合初学者入手的vue项目
  15. 字节跳动不需要总部大楼
  16. android发送短信验证码并自动获取验证码填充文本框
  17. LINUX入门——Linux是什么?
  18. 百度离线地图开发,node实现地图瓦片下载
  19. 开学季·DGUT立Flag =W=
  20. revit二次开发——如何选取元素(revit2016)

热门文章

  1. 仿真物流仓库拣货车拣货
  2. C++ 控制台移动光标
  3. 思博伦Spirent TestCenter - 使用向导模式创建数据流_双极未来
  4. C语言for循环打印各种字符三角形+菱形的方法
  5. 拿到任务后为什么要先分解
  6. 第六章函数与宏定义实验报告(后半部分)
  7. 免费23年的Java开始收费了,程序员怎么办?
  8. 划艇比赛的成绩(利用MATLAB进行验证性实验)
  9. 给你个小写英文字符串 a
  10. 用友BIP智能财务 护航企业业财合一