標籤:javascrip color com 繼承 fine span 類方法 否則 led
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type=text/javascript charset=utf-8> function extend(Child ,Parent){ var F = new Function();//建立一個函數F,跟寫 function F(){};一樣 F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child ; //儲存一下父類的原型對象: 一方面方便解耦 另一方面方便獲得父類的原型對象 Child.superClass = Parent.prototype; //自訂一個子類的靜態屬性 儲存父類的原型對象,寫 Child.superClass = Parent也可以。保證子類中可以找到父類。 alert(Parent.prototype.constructor); alert(Parent); /*function Person( name , age){ this.name = name ; this.age = age ; }*/ alert(Parent.prototype.constructor === Parent);//true //判斷父類的原型對象的構造器 (加保險),Person.prototype = {中不寫constructor: Person ,那麼Parent.prototype.constructor就是Object if(Parent.prototype.constructor == Object.prototype.constructor){ Parent.prototype.constructor = Parent ; //容錯性,就是寫出你不知道的情形。 } } function Person( name , age){ this.name = name ; this.age = age ; } Person.prototype = { sayHello: function(){ alert(‘hello world!‘); } }; Object.defineProperty(Person.prototype , ‘constructor‘ , { enumerable : false , value : Person }); Person.prototype.say = function(){ alert(‘hello world!‘); } function Boy(name , age , sex){ //call,子類就可以直接new Boy(傳3個參數),否則只能通過父類執行個體對象來訪問添加的屬性。 //Person.call(this,name,age); Boy.superClass.constructor=Person,解耦,子類中不寫父類的東西。 Boy.superClass.constructor.call(this , name , age); this.sex = sex ; } extend(Boy , Person); Boy.prototype.sayHello = function(){//覆蓋父類的方法 alert(‘hi javascript!‘); } var b = new Boy(‘張三‘ , 20 , ‘男‘); alert(b.name); //張三 alert(b.sex);//男 b.sayHello();//hi javascript! //調用父類方法 Boy.superClass.sayHello.call(b);//hello world! b.__proto__.__proto__.sayHello();//hello world! b.constructor.prototype.__proto__.sayHello()//hello world! alert(Boy.superClass.constructor); /*function Person( name , age){ this.name = name ; this.age = age ; }*/ </script> </head> <body> </body></html>
第一,子類調用call方法。第二,子類原型對象的建構函式要改變,原型對象和自己對象的構造器指向函數本身(函數本身的prorotype和對象的__proto__指向原型對象)。第三,子類增加一個靜態屬性指向父類的原型對象,辦證子類可以找到父類。第四,子類原型對象新增屬性要寫在creat之後,因為creat之後子類才有了原型對象。function F(){ this.name = "yw"; var age = 32; sch = 890;} var f = new F(); alert(f.name);//ywalert(f.age);//undefinedalert(f.sch);//undefinedalert(window.name);//空F();alert(window.name);//ywvar F = new Function();//建立一個函數F,跟寫 function F(){};一樣//可以直接寫constructor,prototype,不能寫__proto__,_proto__是為了表示對象是怎麼找到類的原型對象的屬性方法的。
js19--繼承終極版本