探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)
需要共享的數(shù)據(jù)就可以寫原型中
原型的作用之一:數(shù)據(jù)共享
屬性需要共享,方法也需要共享:
不需要共享的數(shù)據(jù)寫在構(gòu)造函數(shù)中 需要共享的數(shù)據(jù)寫在原型中下面我們看一個案例
數(shù)據(jù)共享案例每個學(xué)生的名字,年齡,性別都是獨特的,我們要設(shè)置
所有學(xué)生的身高都是188,所有人的體重都是55所有學(xué)生都要每天寫500行代碼所有學(xué)生每天都要吃一個10斤的西瓜
就可以把共有數(shù)據(jù)寫到原型中
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>title</title> <script> function Student(name,age,sex) { this.name=name; this.age=age; this.sex=sex; } // 所有學(xué)生的身高都是188,所有人的體重都是55 // 所有學(xué)生都要每天寫500行代碼 // 所有學(xué)生每天都要吃一個10斤的西瓜 //原型對象 Student.prototype.height='188'; Student.prototype.weight='55kg'; Student.prototype.study=function () { console.log('學(xué)習(xí),寫500行代碼,小菜一碟'); }; Student.prototype.eat=function () { console.log('吃一個10斤的西瓜'); }; //實例化對象,并初始化 var stu=new Student('晨光',57,'女'); console.dir(Student); console.dir(stu);// stu.eat();// stu.study(); </script></head><body></body></html>
打印出來是這樣的
原型還有一種更簡單的方法,下面是對上面案例的修改
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>title</title> <script> function Student(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } //簡單的原型寫法 Student.prototype = { //手動修改構(gòu)造器的指向 constructor:Student, height: '188', weight: '55kg', study: function () {console.log('學(xué)習(xí)好開心啊'); }, eat: function () {console.log('我要吃好吃的'); } }; var stu=new Student('鼎鼎大名',20,'男'); stu.eat(); stu.study(); console.dir(Student); console.dir(stu); </script></head><body></body></html>
例如設(shè)定方法,吃完了玩,玩完了睡
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>title</title> <script> //原型中的方法,是可以相互訪問的 function Animal(name,age) { this.name=name; this.age=age; } //原型中添加方法 // 吃完了就玩 Animal.prototype.eat=function () { console.log('動物吃東西'); this.play(); }; // 玩完了就睡 Animal.prototype.play=function () { console.log('玩球'); this.sleep(); }; Animal.prototype.sleep=function () { console.log('睡覺了'); }; var dog=new Animal('小蘇',20); dog.eat(); //原型對象中的方法,可以相互調(diào)用 </script></head><body></body></html>
到此這篇關(guān)于探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)的文章就介紹到這了,更多相關(guān)探究JavaScript原型數(shù)據(jù)共享與方法共享內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python 實現(xiàn)在無序數(shù)組中找到中位數(shù)方法2. python中復(fù)數(shù)的共軛復(fù)數(shù)知識點總結(jié)3. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享4. HTML DOM setInterval和clearInterval方法案例詳解5. idea重置默認配置的方法步驟6. PHP中file_get_contents設(shè)置header請求頭,curl傳輸選項參數(shù)詳解說明7. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲8. 愛因斯坦謎題的java解答方法9. html清除浮動的6種方法示例10. Springboot整合camunda+mysql的集成流程分析
