久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)

瀏覽:86日期:2023-09-29 18:46:35
數(shù)據(jù)共享什么樣子的數(shù)據(jù)是需要寫在原型中?

需要共享的數(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>

打印出來是這樣的

探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)

原型簡單寫法

原型還有一種更簡單的方法,下面是對上面案例的修改

<!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>

探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)

原型方法共享

例如設(shè)定方法,吃完了玩,玩完了睡

探究JavaScript原型數(shù)據(jù)共享與方法共享實現(xiàn)

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

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 塘沽区| 临沧市| 炉霍县| 台南县| 鹿邑县| 惠水县| 灌云县| 太和县| 镶黄旗| 元江| 周至县| 钦州市| 应城市| 长治县| 遂溪县| 尼勒克县| 武定县| 靖宇县| 东兴市| 宁南县| 余江县| 梧州市| 绿春县| 浪卡子县| 吐鲁番市| 闵行区| 五华县| 常山县| 鄱阳县| 嘉兴市| 南平市| 万载县| 长葛市| 乐陵市| 淮安市| 丰都县| 卢湾区| 洪湖市| 康乐县| 长沙市| 雅安市|