探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)
數(shù)據(jù)共享
什么樣子的數(shù)據(jù)是需要寫在原型中?
需要共享的數(shù)據(jù)就可以寫原型中
原型的作用之一:數(shù)據(jù)共享
屬性需要共享,方法也需要共享:
- 不需要共享的數(shù)據(jù)寫在構(gòu)造函數(shù)中
- 需要共享的數(shù)據(jù)寫在原型中
下面我們看一個案例
數(shù)據(jù)共享案例
每個學生的名字,年齡,性別都是獨特的,我們要設置
所有學生的身高都是188,所有人的體重都是55
所有學生都要每天寫500行代碼
所有學生每天都要吃一個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; } // 所有學生的身高都是188,所有人的體重都是55 // 所有學生都要每天寫500行代碼 // 所有學生每天都要吃一個10斤的西瓜 //原型對象 Student.prototype.height="188"; Student.prototype.weight="55kg"; Student.prototype.study=function () { console.log("學習,寫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("學習好開心啊"); }, eat: function () { console.log("我要吃好吃的"); } }; var stu=new Student("鼎鼎大名",20,"男"); stu.eat(); stu.study(); console.dir(Student); console.dir(stu); </script> </head> <body> </body> </html>
原型方法共享
例如設定方法,吃完了玩,玩完了睡
<!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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于bootstrap寫的一點localStorage本地儲存
這篇文章主要介紹了基于bootstrap寫的一點localStorage本地儲存,需要的朋友可以參考下2017-11-11window.name代替cookie的實現(xiàn)代碼
window.name代替cookie的實現(xiàn)代碼,需要的朋友可以參考下。2010-11-11創(chuàng)建echart多個聯(lián)動的示例代碼
這篇文章主要介紹了創(chuàng)建echart多個聯(lián)動的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11JavaScript通過join函數(shù)連接數(shù)組里所有元素的方法
這篇文章主要介紹了JavaScript通過join函數(shù)連接數(shù)組里所有元素的方法,實例分析了javascript中join函數(shù)的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03