分享

js 继承(一)

 宜宾翠屏区 2019-04-07

// 定义一个动物类
  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;
=================================================

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多