探究JavaScript原型數據共享與方法共享實現
需要共享的數據就可以寫原型中
原型的作用之一:數據共享
屬性需要共享,方法也需要共享:
不需要共享的數據寫在構造函數中 需要共享的數據寫在原型中下面我們看一個案例
數據共享案例每個學生的名字,年齡,性別都是獨特的,我們要設置
所有學生的身高都是188,所有人的體重都是55所有學生都要每天寫500行代碼所有學生每天都要吃一個10斤的西瓜
就可以把共有數據寫到原型中
<!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 = { //手動修改構造器的指向 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(); //原型對象中的方法,可以相互調用 </script></head><body></body></html>
到此這篇關于探究JavaScript原型數據共享與方法共享實現的文章就介紹到這了,更多相關探究JavaScript原型數據共享與方法共享內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
