首页 > 语言 > JavaScript > 正文

谈一谈javascript中继承的多种方式

2024-05-06 15:01:06
字体:
来源:转载
供稿:网友

JS 是没有继承的,不过可以曲线救国,利用构造函数、原型等方法实现继承的功能。

 var o=new Object();

其实用构造函数实例化一个对象,就是继承,这里可以使用Object中的所有属性与方法。那么为什么能访问Object对象的方法,其实访问的是其原型对象的方法,所有的方法都是放在原型中而不是类中。

console.log(o.__proto__ === Object.prototype) // true 继承的本质console.log(o.__proto__ === Object);console.log(Object.__proto__ === Function.prototype);console.log(Function.prototype.__proto__ === Object.prototype);console.log(Number.__proto__ === Function.prototype);

object是万物祖先,Everything is object 嘛。 

1、内置对象都继承自object

var myNumber = new Number(10); //实例化一个数字对象

字符串对象,其实是String对象的一个实例化 

var s = ‘str';

 除了可以访问自身属性方法,还能访问父类属性方法

console.log(s.toUpperCase());console.log(s.toString()); 

2、自定义对象的继承

// 父类  var Person = function(){   this.name='AV老师';   this.test='测试中的毕福剑';  }   Person.prototype={   say:function(){    console.log('呀买碟');   }  }  // 构造函数  var Canglaoshi = function(name,age,cup){   this.name=name;   this.age=age;   this.cup=cup;  }  // 继承person,则拥有person原型中的方法  Canglaoshi.prototype=new Person();  Canglaoshi.prototype.ppp=function(){   console.log('啪啪啪');  }  // 苍老师拥有了person中的方法  var xiaocang=new Canglaoshi('空空',18,'E');  xiaocang.say();  console.log(xiaocang.name);  console.log(xiaocang.age);  console.log(xiaocang.cup);  console.log(xiaocang.test);

3、自定义对象继承的原型链演示

(function() {   //父类   function SuperParent() {    this.name = 'mike';   }   //子类继承父亲 - 二次继承:   function Parent() {    this.age = 12;   }   Parent.prototype = new SuperParent(); //通过原型,形成链条   var parent = new Parent();   console.log("测试父亲可以访问爷爷属性:" + parent.name);   console.log("测试父亲可以访问自己的属性:" + parent.age);   //继续原型链继承 - 三次继承   function Child() { //brother构造    this.weight = 60;   }   Child.prototype = new Parent(); //继续原型链继承   //原型链测试2   //儿子集成爷爷   var child = new Child();   console.log("测试儿子可以访问爷爷的属性:" + child.name); //继承了Parent和Child,弹出mike   console.log("测试儿子可以访问父亲的属性:" + child.age); //弹出12   console.log("测试儿子可以访问自己独特的属性:" + child.weight); //弹出12   //原型链测试   //爷爷可以访问Object中的方法   var test = new SuperParent();   console.log(test.name);   console.log(test.toString());   //访问链: SuperParent构造对象--》SuperParent原型对象--》Object对象--》Obect原型对象(找到toString方法)--》null   console.log(child.name);   //原型链:首先访问Child构造函数,发现没有name属性--》寻找__proto__,判断起指针是否为空--》指向Child原型函数,寻找有没有name属性--》   //---》没有找到,则判断其__proto__属性是否为null,如果不为null,继续搜索--》找到parent对象,检查是否有name属性,没有。。。。  })()            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选