js高级第三天
构造函数+原型+继承
继承在代码中的作用
复用 让构造函数复用一些另外的构造函数中已经写好的代码
子构造函数复用父构造函数
-
子构造函数 既有父构造函数的属性方法 同时 也有自己的一些属性方法
function Father() { } Father.prototype.say = function () { console.log('爸爸的 也是儿子的') } function Son() { } Son.prototype.say = Father.prototype.say const son = new Son() son.say() function Son2() { } Son2.prototype.say2 = function () { console.log('儿子的就是儿子的') } Son2.prototype.say = Father.prototype.say const son2 = new Son2() son2.say() son2.say2()
代码中关键点
原型 prototype 可以让子构造函数 继承 父构造函数 的 一些方法
this
-
call
- 可以调用函数
- call可以修改this的指向
- call可以传递参数
const obj = { name: '悟空', say(a) { console.log(this, a) } } const NewObj = { name: '八戒' } obj.say() obj.say(1) obj.say.call(NewObj) obj.say.call(NewObj, 2)
继承什么
- 方法
- 属性
es6的class
面向对象 优先选中es6 class 来创建对象
class
创建一个类
es6的class 的出现 基本上可以替代了es5的构造函数和原型,使之代码结构上更加简洁。
class Preson {
name = '悟空';
color = '黄色';
say(){
console.log(this.name,this.color)
}
fly(){
console.log(this.name,'起飞')
}
}
const p1 = new Preson()
console.log(p1)
p1.say()
p1.fly()
constructor 构造器
用来接收参数 属性由外部传入 必须使用构造器接收参数
构造函数 被 new 构造器就被 调用
class Preson {
//构造器 用来接收参数 属性由外部传入 必须使用构造器接收参数
// preson 被 new 构造器就被 调用
constructor(name,color){
// this 指向 实例
this.name = name;
this.color = color
}
say(){
console.log(this.name,this.color)
}
}
const p1 = new Preson('悟空','黄色')
console.log(p1)
p1.say()
extends 子类继承父类
实现 子类继承父类 的 属性和方法
class Preson {
name = '悟空';
say(){
console.log(this.name,'叫爸爸')
}
}
// 继承 父亲的属性和方法
class Son extends Preson{}
const son = new Son()
console.log(son)
super()
如果 子类 写了 extends 继承 还要写 constructor 构造器就 必须 调用 super() 固定语法 不然会报错
作用: 调用了父类的构造器,方便给子类的属性赋值
class Preson {
constructor(name,color){
this.name = name;
this.color = color
}
}
// 如果 子类 写了 extends 继承 还要写 constructor 构造器
// 就 必须 调用 super() 固定语法 不然会报错
class Son extends Preson{
constructor(name,color,height,weight){
super(name,color)
this.height = height;
this.weight = weight
}
}
const son = new Son('悟空','黄色',100,200)
console.log(son
this的指向
全局函数的指向
一般来说 this的指向 判断依据 谁调用了 函数 this 指向谁
当我们定义了全局的函数的时候,默认是挂载到了window 全局变量上
全局函数 其实就是 window的一个属性而已 只不过 平时写代码的时候 可以省略这个window
箭头函数没有this指向
箭头函数没有内部的this
修改this的指向 bind ,call,apply
- call 和 apply 会在调用原函数的同时也修改this的指向
- call 直接传递 obj.say.call(newObj,1,2)
- apply 参数 必须是数组 obj.say.apply(newObj,[1,2])
- bind会帮你修改this指向 但是 不会直接调用原函数 而是会返回一个 修改了this指向 的新函数
const fn = obj.say.bind(newObj)
fn(1,2)
- call 和 apply 区别 传递参数的方式不同而已