類的基本定義和生成實(shí)例:class
class Parent{
constructor(name='leilei'){
this.name=name;
}
}
let v_parent=new Parent('ymy');
console.log(v_parent.name) //ymy
類的繼承 :extends
class Parent{
constructor(name='leilei'){
this.name=name;
}
}
class Child extends Parent{
//繼承:子類怎么在自己的構(gòu)造函數(shù)中傳遞參數(shù)
constructor(name='child'){
super(name);//如果不傳參滑凉,子類使用的是父類默認(rèn)的參數(shù);super一定放在構(gòu)造函數(shù)的第一行鬼雀;
this.type='child';
}
}
console.dir(new Child('hello')) //Child類 ==> name='hello',type='child'
類中的getter 和 setter
class Parent{
constructor(name='leilei'){
this.name=name;
}
get longName(){
return 'ymy '+this.name;
}
set longName(value){
this.name=value;
}
}
// 創(chuàng)建實(shí)例
let p1=new Parent();
console.log(p1.longName) //獲取屬性 ymy leilei
p1.longName='tangtang'; //設(shè)置屬性
console.log(p1.longName) //獲取屬性 ymy tangtang
給類中添加靜態(tài)方法 static
注意:static屬性只能用來(lái)設(shè)置類的靜態(tài)方法抛丽,不能用來(lái)設(shè)置類的靜態(tài)屬性
類的靜態(tài)屬性只能通過(guò): 類.key=value;來(lái)設(shè)置
類的靜態(tài)方法手趣,只有類能使用拜轨,實(shí)例不能使用印颤,實(shí)例只能使用原型上的屬性和方法事甜;
class Parent{
constructor(name='leilei'){
this.name=name;
}
//設(shè)置靜態(tài)方法
static tell(){
console.log('tell');
}
}
Parent.sex='gril'; //設(shè)置類的靜態(tài)屬性
Parent.tell() //調(diào)用類的靜態(tài)方法馒疹; tell
類的 prototype 屬性和proto 屬性
大多數(shù)瀏覽器的 ES5 實(shí)現(xiàn)之中佳簸,每一個(gè)對(duì)象都有__proto__屬性,指向?qū)?yīng)的構(gòu)造函數(shù)的prototype屬性
行冰。Class 作為構(gòu)造函數(shù)的語(yǔ)法糖溺蕉,同時(shí)有prototype屬性和__proto__屬性,因此同時(shí)存在兩條繼承鏈悼做。
(1)子類的__proto__屬性疯特,表示構(gòu)造函數(shù)的繼承,總是指向父類肛走。
(2)子類prototype屬性的__proto__屬性漓雅,表示方法的繼承,總是指向父類的prototype屬性朽色。
class A {
}
class B {
}
// B 的實(shí)例繼承 A 的實(shí)例
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
// B 的實(shí)例繼承 A 的靜態(tài)屬性
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;
const b = new B();
最后編輯于 :2018.02.08 09:47:51
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者