今天說一下什么是es6中的類
1.首先說一下用class生成的類
//生成實(shí)例對象的傳統(tǒng)方法是通過構(gòu)造函數(shù)
function Point(x,y){
this.x = x;
this.y = y
}
Point.prototype.toString = function(){
return '(' + this.x+','+this.y+')'
}
var p = new Point(1,2);
//ES6 提供了更接近傳統(tǒng)語言的寫法 引入了Class類這個(gè)概念 ES6 的Class可以看作只是一個(gè)語法糖
class Point{
constructor(x,y){ //構(gòu)造方法
this.x = x;
this.y = y;
}
toString(){
return '('+this.x + ',' +this.y+')';
}
}
//ES6的類 完全可以看做構(gòu)造函數(shù)的另一種寫法
//使用的時(shí)候 也是直接對類使用new命令,跟構(gòu)造函數(shù)用法完全一致
//事實(shí)上類的所有方法都在類的prototype屬性上面
//所以 類.prototype.constructor === 類 true
//constructor方法是類我的默認(rèn)方法,通過new命領(lǐng)生成對象實(shí)例時(shí),自動調(diào)用該方法
//一個(gè)類必須擁有constructor這個(gè)方法 如果沒有的話自動添加 所以
class Point{
}
//等同于
class Point{
constructor(){}
}
//constructor方法默認(rèn)返回實(shí)例對象
//就像使用構(gòu)造函數(shù)一樣運(yùn)用
var point = new Point()
2.繼承
// 繼承
class Parent{ //定義一個(gè)類
constructor(name='小明'){
this.name= name;
}
}
class Child extends Parent{
}
console.log('繼承',new Child()) // 繼承 {name: "小明"}
繼承傳遞參數(shù)
// 繼承傳遞參數(shù)
class Parent{ //定義一個(gè)類
constructor(name='小明'){
this.name= name;
}
}
class Child extends Parent{
constructor(name = 'child'){ // 子類重寫name屬性值
super(name); // 子類向父類修改 super一定放第一行
this.type= 'preson';
}
}
console.log('繼承',new Child('hello')) // 帶參數(shù)覆蓋默認(rèn)值 繼承{name: "hello", type: "preson"}
3.類的super()方法
super關(guān)鍵字出現(xiàn)的前提是使用Class的繼承
class Person { // ... }
class Student extends Person{
constructor(){
super();
}
}
為什么會有super
當(dāng)類使用繼承漏健,并實(shí)例化時(shí)赦肃,
es5 的繼承是先創(chuàng)建子類的this,然后將父類的方法添加到子類的this上去携御;
es6 的繼承是創(chuàng)建父類的this對象,然后再對this對象添加方法/屬性徘熔。
而super方法就是用來創(chuàng)建父類this對象的婆排。
使用super()
const proto = {
foo: 'hello'
};
const obj = {
foo: 'world',
find() {
return super.foo;
}
};
Object.setPrototypeOf(obj, proto);//使用setPrototypeOf給obj設(shè)置原型對象為proto
obj.find() // "hello"
注意:super用來表示原型對象時(shí)荷科,只能用在對象的方法中,用在其他地方都會報(bào)錯席楚。
靜態(tài)方法調(diào)用
靜態(tài)方法中的super指向父類
class Person {
static sport(str) {
console.log(str);
}
}
class Student extends Person {
static log() {
super.sport('調(diào)用到啦RТ蕖!烦秩!');
}
}
Student.log(); // 調(diào)用到啦?逅埂!只祠!
ES6 規(guī)定兜蠕,通過super調(diào)用父類的方法時(shí),方法內(nèi)部的this指向子類抛寝。
實(shí)際上執(zhí)行的是 super.sport.call(this);