[Object]继承(经典版)(一)对象冒充和Call

作者:zccst


先臆想一下这种方法
Js代码  收藏代码
  1. var a = function(){  
  2.     alert(1);  
  3. }  
  4. console.log(a);  
  5. a.m1 = function(){  
  6.     alert(2);  
  7. }  
  8. console.log(typeof a);  
  9. console.log(typeof a.m1);  
  10. a.m1();  
  11. //结论:给函数绑定一个属性,该属性指向另一个函数  







一、对象冒充
Js代码  收藏代码
  1. //对象冒充,是指将父类的属性和方法一起传给子类作为特权属性和特权方法  
  2.   
  3. function Person(name,age){  
  4.     this.name = name;  
  5.     this.age = age;  
  6.     this.sayHi = function(){  
  7.         alert('hi');  
  8.     }  
  9. }  
  10.   
  11. Person.prototype.walk = function(){  
  12.     alert('walk.......');  
  13. }  
  14.   
  15. function Student(name,age,grade){  
  16.     //是指将父类的属性和方法一起传给子类作为特权属性和特权方法。  
  17.     this.newMethod = Person;  
  18.     this.newMethod(name,age);  
  19.     delete this.newMethod;//如果不删除,newMethod还有Person的prototype方法walk  
  20.     this.grade = grade;  
  21. }  
  22.   
  23. var s1 = new Student('xiaoming',10,3);  
  24. console.log(s1);//s1作为Student的对象,拥有父类和子类的属性  
  25. //Student { name="xiaoming", age=10, grade=3, sayHi=function() }  
  26.   
  27. //s1.walk();//报错 s1.walk is not a function  


//结论:Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。



二、call和apply(借用构造函数)

Js代码  收藏代码
  1. //使用call或apply改变对象的作用域来实现继承,让父类的this等于新创建的子类的对象  
  2.   
  3. function Person(name,age){  
  4.     this.name = name;  
  5.     this.age = age;  
  6.     this.sayHi = function(){  
  7.         alert('hi');  
  8.     }  
  9. }  
  10.   
  11. Person.prototype.walk = function(){  
  12.     alert('walk.......');  
  13. }  
  14.   
  15. function Student(name,age,grade){  
  16.     //让父类的this等于新创建的子类的对象  
  17.     Person.call(this, name, age);  
  18.     this.grade = grade;  
  19. }  
  20.   
  21. var s1 = new Student('xiaoming',10,3);  
  22. console.log(s1);//s1作为Student的对象,拥有父类和子类的属性  
  23. //Student { name="xiaoming", age=10, grade=3, sayHi=function() }  
  24.   
  25.   
  26. //s1.walk();//s1.walk is not a function  


//结论:同前面的对象冒充一样,Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。
原文地址:https://www.cnblogs.com/shsgl/p/4289891.html