码迷,mamicode.com
首页 > Web开发 > 详细

JS继承

时间:2019-12-07 16:01:20      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:function   小明   col   tor   fat   func   mon   prototype   cal   

一.JS中的继承

ES6之前由于没有extends属性我们必须通过构造函数+原型对象模拟实现继承,被称为组合继承。

ES6之前:借用父构造函数继承属性

 1 //1.父构造函数
 2 function Father(uname ,age){
 3   this.uname = uname;
 4   this.age = age;
 5 }
 6 
 7 //子构造函数
 8 function Son(uname ,age ,score){
 9 
10   //使用call方法修改this指向子构造函数
11   Father.call(this,uname,age);
12   this.score = score;
13 }
14 
15 var son = new Son("小明",14,100);
16 console.log(son);

技术图片

ES6之前:借用父构造函数+原型对象继承方法

 1 //1.父构造函数
 2 function Father(uname ,age){
 3   this.uname = uname;
 4   this.age = age;
 5 }
 6 
 7 Father.prototype.money = function(){
 8   
 9 }
10 
11 //2.子构造函数
12 function Son(uname ,age ,score){
13 
14   //使用call方法修改this指向子构造函数
15   Father.call(this,uname,age);
16   this.score = score;
17 }
18 
19 //改变原型对象指向
20 Son.prototype = new Father();
21 //还原构造函数
22 Son.prototype.constructor = Son;
23 //添加原型对象方法
24 Son.prototype.exam = function(){
25 
26 }
27 
28 var son = new Son("小明",14,100);
29 console.log(son);

技术图片

 

 

JS继承

标签:function   小明   col   tor   fat   func   mon   prototype   cal   

原文地址:https://www.cnblogs.com/zhihaospace/p/12001734.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!