【每日一題NO.58】JS 中如何實(shí)現(xiàn)一個(gè)類(lèi)?怎么實(shí)例化這個(gè)類(lèi)?

構(gòu)造函數(shù)法
Object.create 法
面向?qū)ο缶幊痰臉?gòu)造
ES6 語(yǔ)法糖 class
構(gòu)造函數(shù)法
用 new 關(guān)鍵字生成實(shí)例對(duì)象。
function?MoonCake(name,?price)?{
??this.name?=?name;
??this.price?=?price;
}
MoonCake.prototype.sell?=?function?()?{
??alert(this.name?+?",?價(jià)格為"?+?this.price);
};
var?moonCake?=?new?MoonCake("冰皮月餅",?100);
moonCake.sell();
缺點(diǎn):
用到了 this 和 prototype,編寫(xiě)復(fù)雜,可讀性差
Object.create 方法
用Object.create()生成實(shí)例對(duì)象。
var?Person?=?{
??firstName:?"小",
??lastName:?"石頭",
??age:?20,
??introduce:?function?()?{
????alert("I?am?"?+?Person.firstName?+?"?"?+?Person.lastName);
??},
};
var?person?=?Object.create(Person);
person.introduce();

Object.create 要求IE9,低版本瀏覽器可以自己仿寫(xiě)一個(gè):
if?(!Object.create)?{
??Object.create?=?function?(o)?{
????function?F()?{}
????F.prototype?=?o;
????return?new?F();
??};
}
其實(shí)Object.create仿寫(xiě)這段代碼就是“原型式繼承”的原理代碼。
具體可以看這篇文章:

PS:更詳細(xì)的polyfill的例子在MDN,做了很多錯(cuò)誤邊界處理,感興趣的可以看 Object.create Polyfill[1]
缺點(diǎn):
不能實(shí)現(xiàn)私有屬性和私有方法,實(shí)例對(duì)象之間也不能共享數(shù)據(jù)。
面向?qū)ο缶幊痰臉?gòu)造
消除 this 和 prototype ,調(diào)用 createNew()得到實(shí)例對(duì)象。
var?Cat?=?{
??age:?13,?//?共享數(shù)據(jù),定義在類(lèi)對(duì)象內(nèi),createNew外
??createNew:?function?()?{
????var?cat?=?{};
????cat.name?=?"喵喵";
????var?sound?=?"呱呱";?//?私有屬性,定義在createNew?內(nèi),輸出對(duì)象外
????cat.makeSound?=?function?()?{
??????alert(sound);?//?暴露私有屬性
????};
????cat.changeAge?=?function?(num)?{
??????Cat.age?=?num;?//?修改共享數(shù)據(jù)
????};
????return?cat;
??},
};
var?cat?=?Cat.createNew();
cat.makeSound();
優(yōu)點(diǎn)
容易理解,結(jié)構(gòu)清晰,符合傳統(tǒng)的面向?qū)ο缶幊痰臉?gòu)造。
缺點(diǎn)
不夠靈活,修改共享數(shù)據(jù)還需要事先定義好。不像原型鏈的形式那樣,實(shí)例類(lèi)可以直接修改。
ES6 語(yǔ)法糖 class
用 new 關(guān)鍵字生成實(shí)例對(duì)象
class?Point?{
??constructor(name,?age)?{
????this.name?=?name;
????this.age?=?age;
??}
??toString()?{
????return?"(name:"?+?this.name?+?",age:"?+?this.age?+?")";
??}
}
var?point?=?new?Point('小石頭',?20);
point.toString()
所有《每日一題》的 知識(shí)大綱索引腦圖 整理在此:https://www.yuque.com/dfe_evernote/interview/everyday
你也可以點(diǎn)擊文末的 “閱讀原文” 快速跳轉(zhuǎn)
參考資料
Object.create Polyfill:?https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create#polyfill

