// 定义一个动物类 function Animal (name) { // 属性 this.name1 = name||'Animal'; // 实例方法 this.sleep = function(){ document.write(this.name + '正在睡觉!'); } } // 原型方法 Animal.prototype.eat = function(food) { document.write(this.name + '正在吃:' + food); }; function Cat(){ } Cat.prototype = new Animal("333333"); //父函数作为实例,成为子函数的一个属性 将父类的实例作为子类的原型 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) ===========================================
借用构造函数 使用call和apply借用其他构造函数的成员, 可以解决给父构造函数传递参数的问题, 但是获取不到父构造函数原型上的成员.也不存在共享问题// 创建父构造函数 function Person(name){ this.name = name; this.freinds = ['小王', '小强']; this.showName = function(){ console.log(this.name); } } // 创建子构造函数 function Student(name){ // 使用call借用Person的构造函数 Person.call(this, name); } // 测试是否有了 Person 的成员 var stu = new Student('Li'); stu.showName(); // Li console.log(stu.friends); // ['小王','小强'] ===================================================
(5) 组合继承 (借用构造函数 + 原型式继承)// 创建父构造函数 function Person(name,age){ this.name = name; this.age = age; this.showName = function(){ console.log(this.name); } } // 设置父构造函数的原型对象 Person.prototype.showAge = function(){ console.log(this.age); } // 创建子构造函数 function Student(name){ Person.call(this,name); } // 设置继承 Student.prototype = Person.prototype; Student.prototype.constructor = Student; =================================================
|