日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

对象(三)

發(fā)布時(shí)間:2025/7/14 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 对象(三) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、原型的弊端

function Person() {}Person.prototype = {constructor : Person,name : 'zs',age : 20,friends : ['王五','趙六']}var p1 = new Person();var p2 = new Person();p2.friends.push("xiao A");alert(p1.friends); // 王五,趙六,xiao Aalert(p2.friends); // 王五,趙六,xiao A// 原型的屬性和方法被所有的對象所共享

改進(jìn)方法一? :?

2、組合原型和構(gòu)造函數(shù)式

function Person2(name, age, friends) {this.name = name;this.age = age;this.friends = friends;}Person2.prototype = {constructor : Person2,sayName : function () {alert(this.name);}}var p3 = new Person2("張三",20,["王五","趙六"]);var p4 = new Person2("李四",26,["王五","趙六","淺淺"])alert(p3.friends) // 王五,趙六p3.sayName(); // 張三alert(p4.friends) // 王五,趙六,淺淺p4.sayName(); // 李四

3、動(dòng)態(tài)原型模式

// 動(dòng)態(tài)原型模式 (將代碼都封裝到一起) function Person3(name,age,friends) {this.name = name;this.age = age;this.friends = friends;if(typeof this.sayName != "function" ){Person3.prototype.sayName = function () {alert(this.name)}}}var p5 = new Person3("haha",20,['aa','bb']);var p6 = new Person3("heihei",22,['aa','bb','cc']);alert(p5.sayName == p6.sayName) // true 說明 sayName 方法只被聲明了一次

4、穩(wěn)妥構(gòu)造函數(shù)式

// 穩(wěn)妥構(gòu)造函數(shù)式 (應(yīng)用在非常安全的環(huán)境中)// 1、沒有公共屬性 2、不能使用 this 對象 function Person4(name,age,job) {// 創(chuàng)建一個(gè)要返回的對象發(fā)var obj = new Object();// 創(chuàng)建一些屬性,屬性為私有屬性,函數(shù)外不能訪問var name = name;obj.sayName = function () { // 函數(shù)里定義方法來訪問函數(shù)內(nèi)的屬性 alert(name);}return obj;}var p7 = new Person4("aa");p7.sayName(); // aa

?

轉(zhuǎn)載于:https://www.cnblogs.com/debra/p/7804500.html

總結(jié)

以上是生活随笔為你收集整理的对象(三)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。