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

首頁 > 編程 > JavaScript > 正文

javascript中的面向?qū)ο?/h1>
2019-11-19 16:58:50
字體:
供稿:網(wǎng)友

相信大家對javascript中的面向?qū)ο髮懛ǘ疾荒吧沁€記得有幾種創(chuàng)建對象的寫法嗎?相信大家除了自己常寫的都有點模糊了,那接下來就由我來幫大家回憶回憶吧!

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

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

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)建具體對象的過程,用函數(shù)來封裝以特定接口創(chuàng)建對象的細節(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. 字面量模式

字面量可以用來創(chuàng)建單個對象,但如果要創(chuàng)建多個對象,會產(chǎn)生大量的重復代碼

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

4. 原型模式

使用原型對象,可以讓所有實例共享它的屬性和方法

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. 組合模式

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

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);

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

// 定義類class Cons{ constructor(name,age){  this.name = name;  this.age = age; } getMes(){  console.log(`hello ${this.name} !`); }}let mesge = new Cons('啦啦啦~',21);mesge.getMes();

在上面的代碼片段里,先是定義了一個Cons類,里面還有一個constructor函數(shù),這就是構(gòu)造函數(shù)。而this關(guān)鍵字則代表實例對象。

而繼承可以通過extends關(guān)鍵字實現(xiàn)。

class Ctrn extends Cons{ constructor(name,anu){  super(name); //等同于super.constructor(x)  this.anu = anu; } ingo(){  console.log(`my name is ${this.name},this year ${this.anu}`); }}let ster = new Ctrn('will',21);ster.ingo();ster.getMes();

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

主站蜘蛛池模板: 龙江县| 北川| 阿图什市| 洛浦县| 海城市| 马山县| 平乡县| 鄂托克前旗| 项城市| 武宁县| 西贡区| 辽宁省| 祁连县| 旌德县| 万州区| 岑巩县| 台北县| 锡林浩特市| 饶阳县| 万盛区| 恩平市| 黎平县| 江都市| 宜良县| 庄河市| 焦作市| 巍山| 兴安盟| 正镶白旗| 巴东县| 桓仁| 定襄县| 老河口市| 紫金县| 美姑县| 云浮市| 阿尔山市| 绵阳市| 金秀| 客服| 澄迈县|