1.如何構造? 先複習一下es5常用的構建類的方法: 1. 首先es5的寫法使用原型進行對象的方法的,為什麼不在構造函數里添加方法呢? 因為實例化對象的時候,會重覆的建立好多相同的方法,浪費資源。所以需要把對象的方法掛載到prtotype里。 2. 關於new和this的綁定問題,可以大概簡化為: ...
1.如何構造?
先複習一下es5常用的構建類的方法:
首先es5的寫法使用原型進行對象的方法的,為什麼不在構造函數里添加方法呢?
因為實例化對象的時候,會重覆的建立好多相同的方法,浪費資源。所以需要把對象的方法掛載到prtotype里。
- 關於new和this的綁定問題,可以大概簡化為:
- 首先通過new生成一個新的對象
- 然後讓這個對象綁定到構造函數的this中去
- 然後綁定這個構造對象的原型對象上
- 最後把這個對象返回給前面定義的對象
那麼接下來看例子吧:
fuction Animal(name,age){
this.name = name
this.age = age
// 這樣是浪費資源的
// this.eat = function(){
// console.log("今天我吃飯了")
// }
}
// 正確做法
Animal.prototype.eat=function(){
console.log("今天我吃飯了")
}
然後上ES6的class,class很明顯就簡化了這個操作
cosnt dog = new Animal("wangcai",2) // 會報錯,ES6為了修改陋習,和let和const一樣,class不會提升.
class Animal{
constroctor(name,age){
this.name = name
this.age = age
}
eat(){
console.log("今天我吃飯了")
}
}
cosnt dog = new Animal("wangcai",2) //正確位置
另外class還添加了靜態方法,set,get等操作。
class Animal{
constroctor(name,age){
this.name = name
this.age = age
}
eat(){
console.log("今天我吃飯了")
}
set name(value){
this.tempname ="老鐵"+value
}
get name(){
return this.tempname
}
static introuduce(){
console.log("我現在是一個動物類")
}
}
//set() get()
const dog = new Animal("giao",2)
dog.name="agiao"
console.log(dog.name) // 老鐵agiao
// 靜態方法
Animal.introuduce() // 我現在是一個動物類
再說繼承之前補充個小知識點,class的方法名可以通過計算屬性的操作來命名
let tempname = "giao"
class Animal{
constroctor(name,age){
this.name = name
this.age = age
}
[tempname](){
console.log("一給我咧giao")
}
}
const xiaoagiao = new Animal("giaoge",30)
xiaoagiao.giao() // 一給我咧giao
2.繼承
回到繼承這個問題,es5是怎麼繼承的呢?
function Animal( name ){
this.name = name
}
Animal.prototype.break(){
console.log("叫!")
}
function Dog( name, age ){
Animal.call(this,name)
this.age = age
}
Dog.prototype = new Animal()
Dog.prototype.constructor = Dog
那麼這個叫組合繼承,怎麼個組合法呢?
屬性方面的繼承是借用繼承,可以看到
Animal.call(this,name)
就是相當於把Animal
這個函數在Dog
的構造函數里調用了一遍而已。雖然屬性他們沒有原型鏈的鏈式聯通,但是代碼拿過來給Dog
都跑了一遍,所以自然就繼承了Animal
的name
屬性。Animal.call(this,name)
方法的繼承是原型式繼承,眾所周知,一個函數會在創建的時候生成一個原型對象,這個函數的的一個
protoype
屬性指向他的原型對象,原型對象的constructor
屬性指向這個函數。如果用new來新建這個函數的實例,這個實例會有一個__proto__
的屬性指向函數的原型對象。所以借用函數實例會指向函數原型對象這個特性,我們將被繼承的函數實例化,然後將這個實例化的對象賦給繼承的構造函數的prototype
屬性,這樣就構成了一種鏈式結構。但同被繼承的函數實例化是不具備constructor這個屬性的,我們需要將他的constructor
指向繼承的構造函數。Dog.prototype = new Animal() Dog.prototype.constructor = Dog
所以按照這個套路,我們用es5的語法,將dog
函數繼承了Animal
函數的name
和break
方法.
那麼ES6是怎麼做的呢?
class Animal{
constructor( name ){
this.name = name
}
break(){
console.log("叫!")
}
}
class Dog extends Animal {
constructor( name, age ){
super(name)
this.age=age
}
}
現在只需要在聲明Dog類的時候加一個extends Animal
,然後再在constructor構造函數裡加一個super就好了。
這個super(name)
就相當於Animal.call(this,name)
了。然後關於方法的問題,自然就不用擔心了,extends自動就處理好了,就不用再去用prototype
亂指了.