背景
class的出現(xiàn),讓js開發(fā)者告別了使用原型對象模仿面向?qū)ο笾械念惡皖惱^承時代。在前端開發(fā)中,使用到class的地方非常之多,所以掌握class的用法已經(jīng)必不可少了。
劃重點
JS 中并沒有一個真正的 class 原始類型, class 僅僅只是對原型對象運用語法糖(PS:什么是語法糖?就是不用寫原始方法,而是提供了一種簡單的寫法,底層還是原始的方法)。所以,只有理解如何使用原型對象實現(xiàn)類和類繼承,才能真正地用好 class?!娟P(guān)于使用原型對象實現(xiàn)類和類繼承詳解,后續(xù)持續(xù)更新】
來看一個class的例子
先記一個知識點:class里面可以寫 三種 方法,第一種是constructor內(nèi)部的方法,第二種是原型鏈上的方法,第三種是static函數(shù)靜態(tài)方法。
class Person{
constructor(name) {
this.name = name;
// constructor內(nèi)部的方法,在 new 一個實例的時候就會生命這個方法,一般情況下也是在內(nèi)部調(diào)用的
function hello1() {
console.log(`hello1 ${name}, this is an inner function!`)
}
hello1()
}
hello2() {
console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 靜態(tài)方法,不需要new就可以調(diào)用
static hello3() {
// 這里的 this.name 返回的是class的名字
console.log(`hello3 ${this.name}, this is a static function!`);
}
}
const p = new Person('orchid');
// 結(jié)果: hello1 orchid, this is an inner function!
p.hello2();
// 結(jié)果: hello2 orchid, this is a prototype function!
Person.hello3();
// 結(jié)果: hello3 Person, this is a static function!
對應(yīng)的原型對象實現(xiàn)
function Person(name) {
this.name = name;
// 與上面的 hello1 對應(yīng)
function hello1() {
console.log(`hello1 ${name}, this is an inner function!`)
}
hello1();
}
// 與上面的 hello2 對應(yīng)
Person.prototype.hello2 = function() {
console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 與上面的 static 方法 hello3 對應(yīng)
Person.hello3 = function() {
console.log(`hello3 ${this.name}, this is a static function!`);
}
const p = new Person('orchid');
// 結(jié)果: hello1 orchid, this is an inner function!
p.hello2();
// 結(jié)果: hello2 orchid, this is a prototype function!
Person.hello3();
// 結(jié)果: hello3 Person, this is a static function!
相信你通過上面的例子已經(jīng)知道了為什么說class只是一種語法糖了,代碼的確是簡單而且容易閱讀了。
上面就是一個將es6轉(zhuǎn)化為原型對象的代碼實現(xiàn)。es6其實就是將class語法轉(zhuǎn)成了原型對象實現(xiàn),底部還是原型對象的代碼。其實class就是一個函數(shù)而已。