一:js中面向对象的特点:
面向对象特点
1、抽象:抽指把核心的东西抽出来,把与我们要解决的问题有关的东西拿出来摆在面前
2、封装:让使用对象的人不考虑内部实现,只考虑功能使用 把内部的代码保护起来,只留出一些个api接口供用户使用
3、继承:就是为了代码的复用,从父类上继承出一些方法和属性,子类也有自己的一些属性
4、多态:实际上是不同对象作用与同一操作产生不同的效果。多态的思想实际上是把“想做什么”和“谁去做“分开
二. js中实现继承的几种方式:
- class类继承
- 构造函数继承
- 原型链继承
- 组合继承
1.1 Class类语法:
- JavaScript 语言中,生成实例对象的传统方法是通过构造函数。
- ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过
class关键字,可以定义类。基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
es6的class类 class是一个关键字 他用于构造一个函数
class Star{
`constructor他是一个构造器 只要有new 他就会立即调用`
constructor(names,ages){
this.name = names
this.age = ages
this.eat = function(){
console.log('我要吃饭');
}
console.log(this);//在class类中this执行实例化出来的对象
}
sing(){
console.log('我会唱歌');
}
}
let s = new Star('刘德华',30)
console.log(s);
s.sing()//sing方法在对象的原型上 原型上的方法所有的实例都可以共享
s.eat()//实例上的方法
1.2 es6中class类实现继承 extends super()
- 图例展示1:
- 图例展示2:
- 代码演示:
<script>
先定义一个父类
class Person{
constructor(name,age){
this.name=name
this.age=age
}
say(){
console.log("讲笑话");
}
}
let p=new Person('老张','30')
再定义一个子类
子类继承父类
class Student extends Person{
constructor(name,age,sex,height){
super() `在访问this之前一定要先调用super 它是用来复制父类的方法`
this.name=name
this.age = age
this.sex=sex
this.height=height
}
study(){
return `我是${this.name},我喜欢学习`
}
}
let s1=new Student('蜡笔小新',18,'男','170')
console.log(s1);
console.log(s1.study());
子类继承父类
class Worker extends Person{
constructor(name,age,money){
super()//在访问this之前一定要先调用super 它是用来复制父类的方法
this.name=name
this.age = age
this.money=money
}
salary(){
return `我是${this.name},我喜欢working`
}
}
let w=new Worker('大boss',38,'10000元')
console.log(w);
console.log(w.salary());
</script>
2.构造函数继承
<script>
// 构造函数的继承
function Animal(name,type,tail){
// console.log(this);
this.names = '动物'
this.type = '头脑简单'
this.tail = '小尾巴'
this.sleep = function(){
console.log('睡觉');
}
console.log(this);//在构造函数中,this指向实例化出来的对象
}
let a = new Animal()
console.log(a);
function Cat(name,color){
this.name = name
this.color = color
this.jump = function(){
console.log('我是自己独有的,不是继承过来的');
}
// 使用call或者apply方法 将父类的构造函数绑定在子类对象上
Animal.apply(this,arguments)
// Animal.call(this,arguments)
}
let cat = new Cat('咪咪','白色的')
console.log(cat);
</script>
3.原型链继承
<script>
// 原型链继承
// 定义父类的构造函数
function Father(){
this.name = 'Tom',
this.age = 20
this.sing =function(){
console.log('唱歌');
}
console.log(this);
}
// let f = new Father()
// console.log(f);
// 定义一个子类的构造函数
function Son(){
this.name = 'Jack'
}
console.log(Son.prototype);// constructor
// 把父类实例化出来的对象赋值给子类的原型
Son.prototype = new Father()
let son = new Son()
console.log(son);
// 可以调用父类的方法
son.sing()
// 原型链继承 把父类实例化出来的对象赋值给 子类的prototype
</script>
二. Ts中的高级继承
2.1 class类
- 构造函数的类型约束
- 普通方法的类型约束
- 类的继承
- 类实现接口
2.2public、protected、private
- public:对当前类、子类和实例化对象都可见 公开的,谁都能用(默认public)
- protected:在当前类和子类可减,对实例对象不可见 受保护的,仅仅类和类的子类能使用
- private :只在当前类中可见,对实例对象和子类不可见 私有的,仅类自己里头才能使用
- 如图例1:
- 如图例2: