<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>面向對象,函數構造方法1</title> </head> <body> </body> <script> /*(function(){}());將變量方法等搞成不同作用域,即封裝某些代碼塊,后加()是為了可以執行*/ (function(){ var n="局部作用域的變量n"; function people(name,age,sex){//people類的構造函數 this.name=name; this.age=age; this.sex=sex; } people.PRototype.n=n; people.prototype.say=function(){ alert("people----say"); } window.people=people;//賦值給window,全局才可以調用 }()); (function(){ function stu(name,age,sex){//stu類的構造函數 this.name=name; this.age=age; this.sex=sex; } stu.prototype=new people();//繼承people類 var speple_say=stu.prototype.say; people.prototype.say=function(){ speple_say.call(this);//子類調用父類的say() alert("stu----say");//重寫父類say() } window.stu=stu;//賦值給window,全局才可以調用 }()); var p=new people('小明','12','男'); p.say(); alert(p.name+" "+p.n); var s=new stu(); s.say(); alert(s.n); </script></html><!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>面向對象,函數構造方法2</title> </head> <body> </body> <script> /*(function(){}());將變量方法等搞成不同作用域,后加()是為了可以執行*/ (function(){ var n="局部變量n"; function people(name){ var _this={};//聲明_this變量是一個空對象 _this.name=name; _this.say=function(){ alert("people----say---"+_this.name); } return _this;//個人覺得people更像是一個方法而不是類 } window.people=people; }()); function stu(name){ var _this=people(name); var supersay=_this.say; _this.say=function(){ supersay.call(_this); alert("stu----say---"+_this.name); } return _this; } var s=stu('jick'); s.say(); </script></html>
新聞熱點
疑難解答