国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

javascript中的面向?qū)ο?/h1>
2024-05-06 15:19:10
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

相信大家對(duì)javascript中的面向?qū)ο髮?xiě)法都不陌生,那還記得有幾種創(chuàng)建對(duì)象的寫(xiě)法嗎?相信大家除了自己常寫(xiě)的都有點(diǎn)模糊了,那接下來(lái)就由我來(lái)幫大家回憶回憶吧!

1. 構(gòu)造函數(shù)模式

通過(guò)創(chuàng)建自定義的構(gòu)造函數(shù),來(lái)定義自定義對(duì)象類(lèi)型的屬性和方法。

function cons(name,age){ this.name = name; this.age = age; this.getMes = function(){  console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons('will',21);mesge.getMes();

2. 工廠模式

該模式抽象了創(chuàng)建具體對(duì)象的過(guò)程,用函數(shù)來(lái)封裝以特定接口創(chuàng)建對(duì)象的細(xì)節(jié)

function cons(name,age){ var obj = new Object(); obj.name = name; obj.age = age; obj.getMes = function(){  console.log(`my name is ${this.name},this year ${this.age}`); } return obj;}var mesge = cons('will',21);mesge.getMes();

3. 字面量模式

字面量可以用來(lái)創(chuàng)建單個(gè)對(duì)象,但如果要?jiǎng)?chuàng)建多個(gè)對(duì)象,會(huì)產(chǎn)生大量的重復(fù)代碼

var cons = { name: 'will', age : 21, getMes: function(){  console.log(`my name is ${this.name},this year ${this.age}`); }}cons.getMes();

4. 原型模式

使用原型對(duì)象,可以讓所有實(shí)例共享它的屬性和方法

function cons(){ cons.prototype.name = "will"; cons.prototype.age = 21; cons.prototype.getMes = function(){  console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons();mesge.getMes();var mesge1 = new cons();mesge1.getMes();console.log(mesge.sayName == mesge1.sayName);//true

5. 組合模式

最常見(jiàn)的方式。構(gòu)造函數(shù)模式用于定義實(shí)例屬性,而原型模式用于定義方法和共享的屬性,這種組合模式還支持向構(gòu)造函數(shù)傳遞參數(shù)。實(shí)例對(duì)象都有自己的一份實(shí)例屬性的副本,同時(shí)又共享對(duì)方法的引用,最大限度地節(jié)省了內(nèi)存。該模式是目前使用最廣泛、認(rèn)同度最高的一種創(chuàng)建自定義對(duì)象的模式

function cons(name,age){ this.name = name; this.age = age; this.friends = ["arr","all"];}cons.prototype = { getMes : function(){  console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons("will",21);var mesge1 = new cons("jalo",21);console.log(mesge.friends);mesge.friends.push('wc'); //還可以操作數(shù)組哈O(∩_∩)O!console.log(mesge.friends);console.log(mesge1.friends);mesge.getMes();mesge1.getMes();console.log(mesge.friends === mesge1.friends);console.log(mesge.sayName === mesge1.sayName);

最后在告訴你個(gè)秘密,ES6引入了類(lèi)(Class),讓對(duì)象的創(chuàng)建、繼承更加直觀了

// 定義類(lèi)class Cons{ constructor(name,age){  this.name = name;  this.age = age; } getMes(){  console.log(`hello ${this.name} !`); }}let mesge = new Cons('啦啦啦~',21);mesge.getMes();            
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 搜索| 宁强县| 巴马| 河源市| 武宁县| 德惠市| 喀喇沁旗| 临猗县| 会宁县| 时尚| 叶城县| 沂南县| 大兴区| 凤阳县| 龙陵县| 呼和浩特市| 承德县| 彰武县| 华容县| 湘阴县| 蒙自县| 阿坝县| 大埔区| 宁河县| 遵化市| 伊春市| 英超| 托里县| 安吉县| 云梦县| 安新县| 三原县| 宁城县| 尚义县| 渝北区| 万盛区| 团风县| 罗田县| 柳林县| 长治市| 达尔|