-
javaScript是基于面向对象的脚本语言
-
Object,Array,RegExp,Function
-
对象:包括属性和方法
-
面向对象三大特征:封装、继承、多态
-
封装:将相同或类似功能抽离出来,方便复用
-
继承:基于某个类,再添加一些新的功能
-
多态:可以对相同名称的函数实现不同功能,但在JS中不明显,通常在js中实现多态可以通过arguments实现
-
-
-
javaScript继承如何实现
-
ES5中,javaScript没有类的概念,主要通过函数模拟类的实现,到了ES6中,通过class定义类
-
解决几个概念
-
类,构造函数,构造器:对相同特征功能的描述
-
对象,实例:由类创建出来的具体的事物
-
原型,原型链:就是所有实例共享的公共属性和方法
-
-
具体如何实现继承
-
ES5方式
-
原型链继承
-
缺点:只能继承方法,不能传参
-
代码实现:
-
-
-
-
//1.第一步先创建一个父类
function Person(name = '无名', age = 0) {
this.name = name
this.age = age
}
//create方法
Person.prototype.create = function() {
console.log(`${this.name}创建新生活`)
}
//2.第二步创建一个子类
function Child(address = '地球人', name) {
this.address = address
}
//原型链继承
Child.prototype = new Person()
const c1 = new Child('王五')
c1.create()
- 借用构造函数继承
-
优点:能实现子类向父类传参
-
缺点:不能继承方法
-
代码:
-
//2.第二步创建一个子类
function Child(name, age, address = '地球人') {
//借用构造函数继承
Person.call(this, name, age)
this.address = address
}
- 组合式继承【常用】
- 组合式继承演示代码:
//1.第一步先创建一个父类
function Person(name = '无名', age = 0) {
this.name = name
this.age = age
}
//create方法
Person.prototype.create = function() {
console.log(`${this.name}创建新生活`)
}
//drive方法
Person.prototype.drive = function() {
console.log(`${this.name}能开车`)
}
//2.第二步创建一个子类
function Child(name, age, address = '地球人') {
//借用构造函数继承
Person.call(this, name, age)
this.address = address
}
//原型链继承
Child.prototype = new Person()
//play方法
Child.prototype.play = function() {
console.log(`${this.name}能打游戏`)
}
const c1 = new Child('王五', 28, '北京')
- ES6方式
-
class实现
-
class格式定义:
-
//创建一个类
class 类名1 {
//构造器
constructor() {
}
方法1() {}
方法2() {}
}
//实例化
new 类名1()
//ES6实现继承
class 子类 extends 父类 {
//构造器
constructor() {
super()
}
方法1() {}
方法2() {}
}
new 类名2
- 演示代码:
//ES6继承
//1.第一步先创建一个父类
class Person {
//构造器
constructor(name = '无名', age = 0) {
this.name = name
this.age = age
}
//原型create方法
create() {
console.log(`${this.name}创建新生活`)
}
//原型drive方法
drive() {
console.log(`${this.name}能开车`)
}
}
class Child extends Person {
constructor(name, age, address = '地球人') {
//super就是父类的意思
super(name, age)
this.address = address
}
//play方法
play() {
console.log(`${this.name}能打游戏`)
}
}
const c1 = new Child('王五', 28, '北京')