// 定義一個(gè)動(dòng)物類 function Animal (name) { // 屬性 this.name1 = name||'Animal'; // 實(shí)例方法 this.sleep = function(){ document.write(this.name + '正在睡覺!'); } } // 原型方法 Animal.prototype.eat = function(food) { document.write(this.name + '正在吃:' + food); }; function Cat(){ } Cat.prototype = new Animal("333333"); //父函數(shù)作為實(shí)例,成為子函數(shù)的一個(gè)屬性 將父類的實(shí)例作為子類的原型 Cat.prototype.name = 'cat'; var cat = new Cat(); alert(cat.name) alert(cat.name1) cat.eat('fish'); cat.sleep(); alert(cat instanceof Animal) alert(cat instanceof Cat) ===========================================
借用構(gòu)造函數(shù) 使用call和apply借用其他構(gòu)造函數(shù)的成員, 可以解決給父構(gòu)造函數(shù)傳遞參數(shù)的問題, 但是獲取不到父構(gòu)造函數(shù)原型上的成員.也不存在共享問題// 創(chuàng)建父構(gòu)造函數(shù) function Person(name){ this.name = name; this.freinds = ['小王', '小強(qiáng)']; this.showName = function(){ console.log(this.name); } } // 創(chuàng)建子構(gòu)造函數(shù) function Student(name){ // 使用call借用Person的構(gòu)造函數(shù) Person.call(this, name); } // 測試是否有了 Person 的成員 var stu = new Student('Li'); stu.showName(); // Li console.log(stu.friends); // ['小王','小強(qiáng)'] ===================================================
(5) 組合繼承 (借用構(gòu)造函數(shù) + 原型式繼承)// 創(chuàng)建父構(gòu)造函數(shù) function Person(name,age){ this.name = name; this.age = age; this.showName = function(){ console.log(this.name); } } // 設(shè)置父構(gòu)造函數(shù)的原型對象 Person.prototype.showAge = function(){ console.log(this.age); } // 創(chuàng)建子構(gòu)造函數(shù) function Student(name){ Person.call(this,name); } // 設(shè)置繼承 Student.prototype = Person.prototype; Student.prototype.constructor = Student; =================================================
|