這篇文章主要介紹es6中類的示例,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

類class
基本概念,記錄以便自己后面加深理解
了解類是什么
class是什么?不妨寫(xiě)一個(gè)看看
class Demo {
constructor() {
this.a = 1;
this.b = this.f;
}
f() {
return this;
}
}
Demo.prototype; //{
// constructor: class Demo
// f: ? f()
// __proto__: Object }Demo的原型可以看到這三個(gè)屬性都是不可遍歷的并且與Demo類相比就多了一個(gè)__proto__原型鏈。我們?cè)賜ew一個(gè)Demo看一下
let o = new Demo();
console.log(Object.getPrototypeOf(o)); //{
// constructor: class Demo
// f: ? f()
// __proto__: Object }實(shí)際上Demo類相當(dāng)于Demo實(shí)例的原型
class中的constructor在我看來(lái)
constructor() {
this.a = 1;
this.b = this.f;
}這部分相當(dāng)于es5中構(gòu)造函數(shù)的作用,在new的過(guò)程中對(duì)this進(jìn)行賦值,并返回this也就成了實(shí)例對(duì)象
因此你在constructor中return了一個(gè)對(duì)象且不等于null那么實(shí)例對(duì)象就是return的值,和es5構(gòu)造函數(shù)一樣的效果
f() {
return this;
}這個(gè)方法最終屬于在實(shí)例對(duì)象的原型鏈上不可遍歷方法,因此也能被實(shí)例對(duì)象使用
新知識(shí)點(diǎn)class的靜態(tài)方法表示該方法不會(huì)被實(shí)例繼承,而是直接通過(guò)類來(lái)調(diào)用
class Demo {
constructor() {
this.a = this;
this.b = this.f;
}
static g() {
return this;
}
static f() {
return this;
}
}
let o = new Demo();
//console.log(o.b()); //not a function
//console.log(o.g()); //not a function
Demo.g() === Demo; //true靜態(tài)方法中的this指向類自己,而this.a = this則指向?qū)嵗龑?duì)象自己
靜態(tài)方法可以被子類繼承
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'靜態(tài)方法可以從super對(duì)象上調(diào)用
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod() // "hello, too"Class 內(nèi)部只有靜態(tài)方法,沒(méi)有靜態(tài)屬性
class表達(dá)式的立即執(zhí)行寫(xiě)法var o = new class {
constructor(n) {
this.a = n;
this.b = this.f;
}
g() {
return n;
}
f() {
return this;
}
}(1)
o.a; // 1class類聲明不存在變量提升
new.target 屬性是在new后返回一個(gè)對(duì)象,例如es5中構(gòu)造函數(shù)f不是通過(guò)new調(diào)用返回undefined,通過(guò)new調(diào)用返回構(gòu)造函數(shù)自己
function f() {
return new.target;
}
console.log((new f()) === f); //true而class類中,則返回class自身。和靜態(tài)方法中this是一樣的;new得是哪個(gè)類就返回哪個(gè)類
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本類不能實(shí)例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 報(bào)錯(cuò)
var y = new Rectangle(3, 4); // 正確以上是“es6中類的示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道!
網(wǎng)頁(yè)標(biāo)題:es6中類的示例-創(chuàng)新互聯(lián)
當(dāng)前鏈接:http://www.chinadenli.net/article32/dpodsc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、虛擬主機(jī)、網(wǎng)站內(nèi)鏈、響應(yīng)式網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站維護(hù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容