標籤:
<!doctype html><html lang="en"> <head> <meta charset="UTF-8"> <title>對象繼承</title> </head> <body> <script> /* function Person(name, age){ this.name = name; this.age = age; this.say = function(){ alert("我的名字是" + this.name); } } function Student(name,id){ this.temp = Person; //臨時屬性方式,對象冒充 this.temp(name); //delete this.temp; this.id = id; this.showId = function(){ alert(‘我是學生,我的學號是:‘ + this.id); } } var stu = new Student(‘zhangsan‘,‘001‘); stu.say(); stu.showId(); */ //***************************************************** /*function Person(name, age){ this.name = name; this.age = age; this.say = function(){ alert("我的名字是" + this.name); } } function Student(name,id){ Person.call(this,name);//call方式實現對象冒充 //Person.apply(this,new Array(name)); //apply方式實現冒充 this.id = id; this.showId = function(){ alert(‘我是學生,我的學號是:‘ + this.id); } } var stu = new Student(‘zhangsan‘,‘001‘); stu.say(); stu.showId(); */ /* 在OO概念中,new執行個體化後,對象就在堆記憶體中形成了自己的空間,值得注意的是,這個程式碼片段。而成員方法就是存在這個程式碼片段的,並且方法是共用的。問題就在這裡,通過對象冒充方式繼承時,所有的成員方法都是指向this的,也就是說new之後,每個執行個體將都會擁有這個成員方法,並不是共用的,這就造成了大量的記憶體浪費。並且通過對象冒充的方式,無法繼承通過prototype方式定義的變數和方法,如以下代碼將會出錯:*/ //*************************************** /*function Person(name){ this.name = name; this.say = function(){ alert("我的名字是" + this.name); } } Person.prototype.age = 20; Person.prototype.sayAge = function(){ alert(‘我的年齡是:‘ + this.age); } function Student(name,id){ //Person.call(this, age); Person.apply(this, new Array(age)); this.id = id; this.showId = function(){ alert(‘我是學生,我的學號是:‘ + this.id); } } var stu = new Student(‘zhangsan‘,‘001‘); stu.sayAge(); //報錯age 未定義 //stu.showId(); */ //********************************************************* //原型繼承方式:此方法實現有缺陷,就是執行個體化子類時不能把參數傳給父類,function Person()沒有參數。 /* function Person(){ this.name = ‘wangwu‘; } Person.prototype.say = function(){ alert(‘my name is :‘ + this.name); } function Student(id){ this.id = id; this.showId = function(){ alert(‘I am a student,my NO is:‘ + this.id); } } Student.prototype = new Person(); var stu = new Student(‘001‘); stu.say();//zhangsan stu.showId(); alert(stu.hasOwnProperty(‘id‘)); */ //******************************************************* //好的繼承方式是,成員變數用對象冒充,成員方法用原型繼承 function Person(name){ this.name = name; } Person.prototype.say = function(){ alert(‘my name is :‘ + this.name); } function Student(name,id){ Person.call(this, name); this.id = id; this.showId = function(){ alert(‘I am a student,my NO is:‘ + this.id); } } Student.prototype = new Person(‘wangwu‘); var stu = new Student(‘zhangsan‘,‘001‘); stu.say();//zhangsan stu.showId(); alert(stu.hasOwnProperty(‘id‘)); </script> </body></html>
對象繼承方式