关于javascript:一次性精通javascript原型继承构造函数类的原理下

上篇咱们解说了构造函数和原型等前端概念的原理,晓得了实例之间如何通过构造函数的prototype来共享方法,下篇咱们次要看下用es6的class怎么来实现,以及class的继承等。同上篇一样,重点在于背地的原理,只有懂得了为什么要这么设计,咱们能力真正的说【精通】。

如果下篇你看得很辛苦,那阐明你对原型的把握还不够啊喂,请务必先熟读了解上篇。

ES6的class

回顾下之前es5的写法:

function User(name, age) {
    this.name = name
    this.age = age
}

User.prototype.grow = function(years) {
    this.age += years
    console.log(`${this.name} is now ${this.age}`)
}
User.prototype.sing = function(song) {
    console.log(`${this.name} is now singing ${song}`)
}

const zac = new User('zac', 28)

es6的写法:

class User {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    grow(years) {
        this.age += years
        console.log(`${this.name} is now ${this.age}`)
    }
    sing(song) {
        console.log(`${this.name} is now singing ${song}`)
    }
}

const zac = new User('zac', 28)

当咱们调用new User('zac', 28)时:

  1. 创立了一个新对象zac
  2. constructor办法主动运行一次,同时把传参'zac', 28赋值给新对象

所以这个class到底是什么呢?其实class就是个函数而已。

console.log(typeof User) // function

那么class背地到底是怎么运作的呢?

  1. 首先创立了一个叫做User的函数
  2. 而后把class的constructor外面的代码一成不变的放到User函数里
  3. 最初将class的办法,如grow,sing放到User.prototype里

完事,看到了吗?javascript的class只是构造函数的语法糖而已(当然class还做了一些其余的小工作)

es6为咱们引进了类class的概念,看起来更靠近其余面向对象编程的语言了,但不同于其余oop语言的类继承,javascript的继承依然是通过原型来实现的。

ES6的extend

咱们接下来看class之间的继承要怎么实现,es6为咱们提供了一个extends的办法:

class User {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    grow(years) {
        this.age += years
        console.log(`${this.name} is now ${this.age}`)
    }
    sing(song) {
        console.log(`${this.name} is now singing ${song}`)
    }
}

class Admin extends User {
    constructor(name, age, address) {
        super(name, age) //to call a parent constructor
        this.address = address
    }
    grow(years) {
        super.grow(years) // to call a parent method
        console.log(`he is admin, he lives in ${this.address}`)
    }
}

const zac = new User('zac', 28)

这里咱们重点看下两次super的调用,首先要明确的是super关键词是class提供给咱们的。次要有两个用法:

  1. super(...)是用来调用父类的constructor办法(只能在constructor里这么调用)
  2. super.method(...)是用来调用父类的办法

覆写父类的constructor

咱们当初离开来看这两点,先解决第一个问题:为什么要在子类的constructor里调用一下super()?起因很简略,因为javascript规定了:通过继承(extends)来而的class,必须在constructor里调用super(),否则在constructor里调用this会报错!

不信你看:

class Admin extends User {
    constructor(name, age, address) {
        this.name = name
        this.age = age
        this.address = address
    }
    ...
}

const zac = new admin('zac', 28, 'China') 
// VM1569:3 Uncaught ReferenceError: 
// Must call super constructor in derived class before accessing 'this' or returning from derived constructor

简略的解释下,javascript为什么这么设计:
因为当应用new来实例化class时,间接创立的class和通过extends来创立的class有一个本质区别:

  1. 前者会先创立一个空对象,而后把这个空对象赋值给this
  2. 后者则间接不做这件事,因为它只须要等本人的父类做这个事就行了

所以,子类必须在本人的construtor里调用super()来让它的父类去执行父类的constructor,否则this就不会被创立,而后如上例所示咱们就失去一个error。

在react里为什么要写super(props)?

顺便说一句,当初你应该能了解为什么咱们在写react组件时,为什么要写这句super(props)了吧?

class Checkbox extends React.Component {
  constructor(props) {
    // 当初你还无奈应用this
    super(props);
    // 当初你能够应用this啦
    this.state = { isOn: true };
  }
  // ...
}

当然这里还有有个小问题,如果我不传props会怎么super()

// React外部的代码
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// 咱们本人代码
class Checkbox extends React.Component {
  constructor(props) {
    super(); 
    console.log(this.props); // undefined   
  // 
}

这个不难理解吧?你不把props传给父组件,天然无奈在constructor里调用this.props咯。但其实你在其余中央还是能够失常调用this.props的,因为react帮咱们多做了一件事:

  // React外部的代码
  const instance = new YourComponent(props);
  instance.props = props;

覆写父类的办法

相对来说,super.method()就好了解多了。咱们的父类User里有一个grow的办法,咱们的子类Admin也想有这个办法,同时可能还想在这个办法上再加点别的操作。所以呢,它就先通过class提供的super来先调用一遍父类的grow办法,而后再增加本人的逻辑。

这里有一些爱思考的同学可能就会想了,为什么我能够通过super来调用父类的办法呢?为什么我能够写super.method()呢?如果你在思考这个问题,阐明你真的很爱思考,你很棒!

简略来了解,既然super.method()是调用父类的办法,而咱们的子类又是通过继承父类而来的,联合之前讲过的原型的常识,那super.method()是不是就应该相当于this.__proto__.method呢?直观上来说的确应该如此,咱们做个简略的试验来看下:

let user = {
  name: "User",
  sing() {
    console.log(`${this.name} is singing.`)
  }
}

let admin = {
  __proto__: user,
  name: "Admin",
  sing() {
    this.__proto__.sing.call(this) //(*)
    console.log('calling from admin')
  }
}

admin.sing(); // Admin is singing. calling from admin

能够看到,user对象是admin对象的原型,次要看下(*)这句话,咱们在以后对象的上下文(this)里调用了原型对象user的sing办法。留神我用了.call(this),如果没有这个的话,咱们执行this.__proto__.sing()时是在原型对象user的上下文里执行的,所以执行this.name时this指向的是user对象:

...
let admin = {
  __proto__: user,
  name: "Admin",
  sing() {
    this.__proto__.sing()
    console.log('calling from admin')
  }
}

admin.sing(); // User is singing. calling from admin

这里顺便解释下this,敲黑板了,不论你是在对象里还是原型了发现了this,它永远是点(.)右边的那个对象。如果是user.sing()那this是(.)右边的user;如果admin.sing()那this就是(.)右边的admin。

而后咱们再看下下面的例子,咱们调用的办法是admin.sing(),所以运行admin中的sing办法时,this就是admin,因而:

  1. 如果是this.__proto__.sing(),调用者是this.__proto__,相当于admin.__proto__, 也就是user对象,所以最初打印进去的是:User is singing.
  2. 如果是this.__proto__.sing.call(this),这时候咱们通过call手动将调用者改为admin了,所以最初打印进去是:Admin is singing.

好了,有点扯远了,咱们再回来。刚刚的例子如同的确证实了super.method()相当于this.__proto__.method,咱们再看上面的代码:

let user = {
  name: "User",
  sing() {
    console.log(`${this.name} is singing.`)
  }
}

let admin = {
  __proto__: user,
  name: "Admin",
  sing() {
    this.__proto__.sing.call(this) //(*)
    console.log('calling from admin')
  }
}

let superAdmin = {
  __proto__: admin,
  name: "SuperAdmin",
  sing() {
    this.__proto__.sing.call(this) //(**)
    console.log('calling from superAdmin')
  }
}

superAdmin.sing(); // VM1900:12 Uncaught RangeError: Maximum call stack size exceeded

运行下面的代码,马上就报错了,报错通知咱们超过了最大调用栈的范畴,这个错个别阐明咱们的代码呈现里有限循环调用。咱们再来逐层解析:

  1. 首先咱们来看调用办法是:superAdmin.sing(),所以运行第(**)句时,this=superAdmin,因而:
this.__proto__.sing.call(this) //(**)
//相当于
superAdmin.__proto__.sing.call(this)
//相当于
admin.sing.call(this) //相当于咱们去执行admin里的sing办法时,this依然是superAdmin
  1. 而后就运行到了第(*)句,这时候this=superAdmin,因而:
this.__proto__.sing.call(this) //(*)
//相当于
superAdmin.__proto__.sing.call(this)
//相当于
admin.sing.call(this) //又回到了这里

而后,终局你就晓得,admin.sing一直循环地调用者本人。所以啊,单纯的通过this是无奈解决这个问题的。javascript为了解决这个问题设计了一个新的外部属性[[HomeObject]],每当一个函数被指定为一个对象的办法时,这个办法就有了一个属性[[HomeObject]],这个属性固定的指向这个对象:


let user = {
  name: "User",
  sing() { 
    console.log(`${this.name} is singing.`)
  }
}

//admin.sing.[[HomeObject]] == admin
let admin = {
  __proto__: user,
  name: "Admin",
  sing() {   
    super.sing()
    console.log('calling from admin')
  } 
}

// admin.sing.[[HomeObject]] == admin
let superAdmin = {
  __proto__: admin,
  name: "SuperAdmin",
  sing() {
    super.sing() 
    console.log('calling from superAdmin')
  }
} 

superAdmin.sing()
// SuperAdmin is singing.
// calling from admin 
// calling from superAdmin

ok,当咱们运行superAdmin.sing()时,也就是执行super.sing(),每当super关键词呈现,javascript引擎就会去找以后办法的[[HomeObject]]对象,而后去找这个对象的原型,最初在这个原型上调用相应的办法。

所以当咱们调用superAdmin.sing()时,相当于执行:

const currentHomeObject = this.sing.[[HomeObject]]
const currentPrototype = Object.getPrototypeOf(currentHomeObject)
currentPrototype.sing.call(this)

ES5如何实现extends

上面咱们比照的来看下,es5是怎么实现extends语法的:

function User(name, age) {
    this.name = name
    this.age = age
}

User.prototype.grow = function(years) {
    this.age += years
    console.log(`${this.name} is now ${this.age}`)
}
User.prototype.sing = function(song) {
    console.log(`${this.name} is now singing ${song}`)
}

function Admin(name, age, address) {
    User.call(this, name, age)
    this.address = address
}

Admin.prototype = Object.create(User.prototype)
Admin.prototype.grow = function(years) {
        User.prototype.grow.call(this, years)
        console.log(`he is admin, he lives in ${this.address}`)
}
Admin.prototype.constructor = User



const zac = new Admin('zac', 28, 'China')

好,先写到这里,剩下的早晨再更新…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理