企业网站建设熊掌号,wordpress教程 2015,服务器怎么做看视频的网站,成都市公园城市建设管理局网站文章目录 一、class方式定义类1.认识class定义类2.类和构造函数的异同3.类的构造函数4.类的实例方法5.类的访问器方法6.类的静态方法 二、继承1.extends实现继承2.super关键字3.继承内置类4.类的混入mixin 三、ES6转ES51.class转换2.extends转换 四、多态 一、class方式定义类 … 文章目录 一、class方式定义类1.认识class定义类2.类和构造函数的异同3.类的构造函数4.类的实例方法5.类的访问器方法6.类的静态方法 二、继承1.extends实现继承2.super关键字3.继承内置类4.类的混入mixin 三、ES6转ES51.class转换2.extends转换 四、多态 一、class方式定义类
1.认识class定义类
我们会发现按照前面的构造函数形式创建类不仅仅和编写普通的函数过于相似而且代码并不容易理解。
在ES6ECMAScript2015新的标准中使用了class关键字来直接定义类但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系
那么如何使用class来定义一个类呢
可以使用两种方式来声明类类声明和类表达式
// 方式一 类声明
class Person {}// 方式二 类表达式
var Student class {}2.类和构造函数的异同
我们来研究一下类的一些特性
你会发现它和我们的构造函数的特性其实是一致的
// function定义类
function Person1(name, age) {this.name namethis.age age
}Person1.prototype.running function() {}
Person1.prototype.eating function() {}var p1 new Person1(why, 18)
console.log(p1.__proto__ Person1.prototype)
console.log(Person1.prototype.constructor)
console.log(typeof Person1) // function// 不同点: 作为普通函数去调用
Person1(abc, 100)// class定义类
class Person2 {constructor(name, age) {this.name namethis.age age}running() {}eating() {}
}var p2 new Person2(kobe, 30)
console.log(p2.__proto__ Person2.prototype)
console.log(Person2.prototype.constructor)
console.log(typeof Person2)// 不同点: class定义的类, 不能作为一个普通的函数进行调用
Person2(cba, 0)3.类的构造函数
如果我们希望在创建对象的时候给类传递一些参数这个时候应该如何做呢
每个类都可以有一个自己的构造函数方法这个方法的名称是固定的constructor当我们通过new操作符操作一个类的时候会调用这个类的构造函数constructor每个类只能有一个构造函数如果包含多个构造函数那么会抛出异常
当我们通过new关键字操作类的时候会调用这个constructor函数并且执行如下操作 在内存中创建一个新的对象空对象 这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性 构造函数内部的this会指向创建出来的新对象 执行构造函数的内部代码函数体代码 如果构造函数没有返回非空对象则返回创建出来的新对象
class Person {constructor(name, age) {this.name namethis.age age}
}4.类的实例方法
在上面我们定义的属性都是直接放到了this上也就意味着它是放到了创建出来的新对象中
在前面我们说过对于实例的方法我们是希望放到原型上的这样可以被多个实例来共享这个时候我们可以直接在类中定义
class Person {constructor(name, age) {this.name namethis.age age}run(){console.log(this.name running~)}
}5.类的访问器方法
我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的那么类也是可以的
class Student {constructor(name, age) {this._name namethis._age age}set name(name) {this._name name}get name() {return this._name}
}
var s new Student(abc, 123)
console.log(s.name)扩展回顾对象的访问器方法 // 针对对象
// 方式一: 描述符
// var obj {
// _name: why
// }
// Object.defineProperty(obj, name, {
// configurable: true,
// enumerable: true,
// set: function() {
// },
// get: function() {
// }
// })// 方式二: 直接在对象定义访问器
// 监听_name什么时候被访问, 什么设置新的值
var obj {_name: why,// setter方法set name(value) {this._name value},// getter方法get name() {return this._name}
}obj.name kobe
console.log(obj.name)访问器的应用场景
// 2.访问器的应用场景
class Rectangle {constructor(x, y, width, height) {this.x xthis.y ythis.width widththis.height height}get position() {return { x: this.x, y: this.y }}get size() {return { width: this.width, height: this.height }}
}var rect1 new Rectangle(10, 20, 100, 200)
console.log(rect1.position)
console.log(rect1.size)6.类的静态方法
静态方法通常用于定义直接使用类来执行的方法不需要有类的实例使用static关键字来定义
// function Person() {}
// // 实例方法
// Person.prototype.running function() {}
// // 类方法
// Person.randomPerson function() {}// var p1 new Person()
// p1.running()
// Person.randomPerson()// class定义的类
var names [abc, cba, nba, mba]
class Person {constructor(name, age) {this.name namethis.age age}// 实例方法running() {console.log(this.name running~)}eating() {}// 类方法(静态方法)static randomPerson() {console.log(this)var randomName names[Math.floor(Math.random() * names.length)]return new this(randomName, Math.floor(Math.random() * 100))}
}var p1 new Person()
p1.running()
p1.eating()
var randomPerson Person.randomPerson()
console.log(randomPerson)二、继承
1.extends实现继承
前面我们花了很大的篇幅讨论了在ES5中实现继承的方案虽然最终实现了相对满意的继承机制但是过程却依然是非常繁琐的。
在ES6中新增了使用extends关键字可以方便的帮助我们实现继承
class Person {}
class Student extends Person {}示例代码
// 定义父类
class Person {constructor(name, age) {this.name namethis.age age}running() {console.log(running~)}eating() {console.log(eating~)}
}class Student extends Person {constructor(name, age, sno, score) {// this.name name// this.age agesuper(name, age)this.sno snothis.score score}// running() {// console.log(running~)// }// eating() {// console.log(eating~)// }studying() {console.log(studying~)}
}var stu1 new Student(why, 18, 111, 100)
stu1.running()
stu1.eating()
stu1.studying()class Teacher extends Person {constructor(name, age, title) {// this.name name// this.age agesuper(name, age)this.title title}// running() {// console.log(running~)// }// eating() {// console.log(eating~)// }teaching() {console.log(teaching~)}
}2.super关键字
我们会发现在上面的代码中我使用了一个super关键字这个super关键字有不同的使用方式
注意在子派生类的构造函数中使用this或者返回默认对象之前必须先通过super调用父类的构造函数super的使用位置有三个子类的构造函数、实例方法、静态方法
class Animal {running() {console.log(running)}eating() {console.log(eating)}static sleep() {console.log(static animal sleep)}
}class Dog extends Animal {// 子类如果对于父类的方法实现不满足(继承过来的方法)// 重新实现称之为重写(父类方法的重写)running() {console.log(dog四条腿)// 调用父类的方法super.running()// console.log(running~)// console.log(dog四条腿running~)}static sleep() {console.log(趴着)super.sleep()}
}var dog new Dog()
dog.running()
dog.eating()Dog.sleep()3.继承内置类
我们也可以让我们的类继承自内置类比如Array
// 1.创建一个新的类, 继承自Array进行扩展
class HYArray extends Array {get lastItem() {return this[this.length - 1]}get firstItem() {return this[0]}
}var arr new HYArray(10, 20, 30)
console.log(arr)
console.log(arr.length)
console.log(arr[0])
console.log(arr.lastItem)
console.log(arr.firstItem)// 2.直接对Array进行扩展
Array.prototype.lastItem function() {return this[this.length - 1]
}var arr new Array(10, 20, 30)
console.log(arr.__proto__ Array.prototype)
console.log(arr.lastItem())// 函数apply/call/bind方法 - Function.prototype4.类的混入mixin
JavaScript的类只支持单继承也就是只能有一个父类
那么在开发中我们我们需要在一个类中添加更多相似的功能时应该如何来做呢
这个时候我们可以使用混入mixin
// JavaScript只支持单继承(不支持多继承)
function mixinAnimal(BaseClass) {return class extends BaseClass {running() {console.log(running~)}}
}function mixinRunner(BaseClass) {return class extends BaseClass {flying() {console.log(flying~)}}
}class Bird {eating() {console.log(eating~)}
}// var NewBird mixinRunner(mixinAnimal(Bird))
class NewBird extends mixinRunner(mixinAnimal(Bird)) {
}
var bird new NewBird()
bird.flying()
bird.running()
bird.eating()三、ES6转ES5
1.class转换
ES6的代码
class Person {constructor(name, age) {this.name namethis.age age}running() {}eating() {}static randomPerson() {}
}var p1 new Person()ES5的代码
use strict;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);Object.defineProperty(Constructor, prototype, { writable: false });return Constructor;
}// 纯函数: 相同输入一定产生相同的输出, 并且不会产生副作用
var Person /*#__PURE__*/ (function () {debuggerfunction Person(name, age) {_classCallCheck(this, Person);this.name name;this.age age;}_createClass(Person,[{key: running,value: function running() {}},{key: eating,value: function eating() {}}],[{key: randomPerson,value: function randomPerson() {}}]);return Person;
})();var p1 new Person(why, 18)2.extends转换
ES6的代码
class Person {constructor(name, age) {this.name namethis.age age}running() {}eating() {}static randomPerson() {}
}class Student extends Person {constructor(name, age, sno, score) {super(name, age)this.sno snothis.score score}studying() {}static randomStudent() {}
}var stu new Student()ES5的代码
use strict;function _typeof(obj) {babel/helpers - typeof;return ((_typeof function typeof Symbol symbol typeof Symbol.iterator? function (obj) {return typeof obj;}: function (obj) {return obj function typeof Symbol obj.constructor Symbol obj ! Symbol.prototype? symbol: typeof obj;}),_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 }});Object.defineProperty(subClass, prototype, { writable: false });if (superClass) _setPrototypeOf(subClass, superClass);
}function _setPrototypeOf(o, p) {_setPrototypeOf Object.setPrototypeOf? Object.setPrototypeOf.bind(): 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 hasnt been initialised - super() hasnt 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.bind(): 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);Object.defineProperty(Constructor, prototype, { writable: false });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() {}},{key: eating,value: function eating() {}}],[{key: randomPerson,value: function randomPerson() {}}]);return Person;
})();function inherit(SubType, SuperType) {SubType.prototype Object.create(SuperType.prototype)SubType.prototype.constructor SubType
}var Student /*#__PURE__*/ (function (_Person) {_inherits(Student, _Person);var _super _createSuper(Student);function Student(name, age, sno, score) {var _this;_classCallCheck(this, Student);_this _super.call(this, name, age);_this.sno sno;_this.score score;return _this;}_createClass(Student,[{key: studying,value: function studying() {}}],[{key: randomStudent,value: function randomStudent() {}}]);return Student;
})(Person);var stu new Student(why, 18, 111, 100);四、多态
面向对象的三大特性封装、继承、多态。
维基百科对多态的定义多态英语polymorphism指为不同数据类型的实体提供统一的接口或使用一个单一的符号来表示多个不同的类型。
非常的抽象个人的总结不同的数据类型进行同一个操作表现出不同的行为就是多态的体现。
那么从上面的定义来看JavaScript是一定存在多态的。
// 多态的表现: JS到处都是多态
function sum(a1, a2) {return a1 a2
}sum(20, 30)
sum(abc, cba)// 多态的表现
var foo 123
foo Hello World
console.log(foo.split())
foo {running: function() {}
}
foo.running()
foo []
console.log(foo.length)