继承方法

原型继承 (继承私有和公有的)

function Fn() {
   this.x =100;
}
Fn.a =1;// {a:1,arguments:null,prototype:{}}
Fn.a只是把Fn当作对象角色,添加了a属性,和prototype是并列的
Fn.prototype.getX = function () {
  console.log(this.x);
}
var f = new Fn;
f.getX();// f通过__proto__找到父类Fn原型中的方法,也就是说f继承了Fn原型中的方法;
// console.log(f.a);
  • 原型继承:通过类A new出来的实例覆盖了B的默认原型的空间地址,那么通过类B创建的实例既可以使用类A实例的私有属性,也可以调用类A原型上的公有属性;类继承了类A公有和私有属性,这种继承方式就是原型继承;
B.prototype=new A;// {getX:function(){}}
var a = new A;//
var b = new B;
//a.haowan();
b.haowan();
b.getX();
  • 原型继承的案例
function A() {
   this.getX=function () {
       console.log(100);
   }
   function getY() {
   }
}
A.prototype.haowan=function () {
   console.log("天下雨了快")
}
function B() {
}
B.prototype=new A;// {getX:function(){}},new A把B的原型重新赋值
//var a = new A;//
var b = new B;
//a.haowan();
b.haowan();
b.getX();

在这里插入图片描述

中间类继承(继承公有属性)

function sum() {
//console.log(arguments);
// 把arguments中__proto__指向了数组Array 的原型;那么arguments就可以通过__proto__找到数组中原型中的方法,并且使用;
在IE10及以下,不兼容;
arguments.__proto__=Array.prototype;
arguments.pop();
// console.log(arguments);
}
sum(12,3,4,5,73,6)

call继承(继承私有属性)

function A() {
    this.haowan=100;
}
A.prototype.getY = function () {
}
function B() {
	//this-->b;也就是B的实例
    this.a=200;
    A.call(this);//改变A中的this,指向类B的实例;让A函数运行
}
var a = new A;
var b = new B;
console.log(b.haowan);//100

寄生组合继承(继承公有和私有)

function A() {
     this.x=100;
 }
 A.prototype.getX =function () {

 }
 function B() {
     A.call(this)
 }
 // 让B的原型中的__proto__指向A的原型;那么通过类B创建的实例;既可以使用A的私有属性,也可以使用公有属性;
 //B.prototype=A.prototype;
 B.prototype = Object.create(A.prototype);// {__proto__:A.prototype}
 B.prototype.getY = function () {
 }
 var b = new B;
 console.log(b.constructor);// A
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值