1.16 JavaScript7:面向物件
面向過程與面向物件程式設計
1、面向過程:所有的工作都是現寫現用。
2、面向物件:是一種程式設計思想,許多功能事先已經編寫好了,在使用時,只需要關注功能的運用,而不需要這個功能的具體實現過程。
javascript物件
將相關的變數和函式組合成一個整體,這個整體叫做物件,物件中的變數叫做屬性,變數中的函式叫做方法。javascript中的物件類似字典。
建立物件的方法
1、單體
<script type="text/javascript"> var Tom = { name : 'tom', age : 18, showname : function(){ alert('我的名字叫'+this.name); }, showage : function(){ alert('我今年'+this.age+'歲'); } } </script>
2、工廠模式
<script type="text/javascript"> function Person(name,age,job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.showname = function(){ alert('我的名字叫'+this.name); }; o.showage = function(){ alert('我今年'+this.age+'歲'); }; o.showjob = function(){ alert('我的工作是'+this.job); }; return o; } var tom = Person('tom',18,'程式員'); tom.showname(); </script>
2、建構函式
<script type="text/javascript"> function Person(name,age,job){ this.name = name; this.age = age; this.job = job; this.showname = function(){ alert('我的名字叫'+this.name); }; this.showage = function(){ alert('我今年'+this.age+'歲'); }; this.showjob = function(){ alert('我的工作是'+this.job); }; } var tom = new Person('tom',18,'程式設計師'); var jack = new Person('jack',19,'銷售'); alert(tom.showjob==jack.showjob); </script>
3、原型模式
<script type="text/javascript"> function Person(name,age,job){ this.name = name; this.age = age; this.job = job; } Person.prototype.showname = function(){ alert('我的名字叫'+this.name); }; Person.prototype.showage = function(){ alert('我今年'+this.age+'歲'); }; Person.prototype.showjob = function(){ alert('我的工作是'+this.job); }; var tom = new Person('tom',18,'程式設計師'); var jack = new Person('jack',19,'銷售'); alert(tom.showjob==jack.showjob); </script>
4、繼承
<script type="text/javascript"> function fclass(name,age){ this.name = name; this.age = age; } fclass.prototype.showname = function(){ alert(this.name); } fclass.prototype.showage = function(){ alert(this.age); } function sclass(name,age,job) { fclass.call(this,name,age); this.job = job; } sclass.prototype = new fclass(); sclass.prototype.showjob = function(){ alert(this.job); } var tom = new sclass('tom',19,'全棧工程師'); tom.showname(); tom.showage(); tom.showjob(); </script>
-
學院Go語言視訊主頁
ofollow,noindex" target="_blank">https://edu.csdn.net/lecturer/1928 -
掃碼獲取海量視訊及原始碼 QQ群:721929980