js继承的三种方式

来源:互联网 发布:暴力营销软件 编辑:程序博客网 时间:2024/05/17 08:02
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><script>// 1、原型继承//原型继承的特点:既继承了父类的模板,又继承了父类的原型对象 // 父类 构造函数 supfunction Sup(name,sex){        this.name = name;        this.sex = sex;}// 父类原型对象Sup.prototype = {constructor:Sup,sayName:function(){alert(this.name)}}// 子类构造函数function Son(age){this.age = age;}    Son.prototype = new Sup("zj");  var b = new Son();  alert(b.name);  b.sayName();  // 2、类继承(只继承父类的模板,不继承原型对象)  // 父类 构造函数 sup  function Sup(name,sex){        this.name = name;        this.sex = sex;}// 父类原型对象Sup.prototype = {constructor:Sup,sayName:function(){alert(this.name)}}// 子类构造函数function Son(name,sex,age){// call applaySup.call(this,name,sex);this.age = age;}var b = new Son("zj","male",20);  alert(b.name+b.sex+b.age);  // b.sayName();不继承原型对象  // 3.混合继承(原型继承 + 借用构造函数继承)  // 父类 构造函数 sup function Sup(name,sex){        this.name = name;        this.sex = sex;}// 父类原型对象Sup.prototype = {constructor:Sup,sayName:function(){alert(this.name)}}// 子类构造函数function Son(name,sex,age){// call applaySup.call(this,name,sex);//借用构造函数继承  继承父类模板this.age = age;}// 接下来继承原型Son.prototype = new Sup();//继承父类的原型对象var b = new Son("zj","male",20);  alert(b.name+b.sex+b.age);  b.sayName();//继承原型对象</script></body></html>

0 0
原创粉丝点击