javascrip --- > 构造函数的继承

两点需要注意的.
第一是在构造函数声明时,会同时创建一个该构造函数的原型对象,而该原型对象是继承自Object的原型对象

// 声明一个构造函数Rectengle
function Rectangle(length, width) {
    this.length = length;
    this.width = width;
}

// 即:看见function 后面函数名是大写,一般认为其是一个构造函数,同时函数都会有一个prototype属性
// Rectangle.prototype的[[Prototype]]属性默认指向Object.prototype属性.
// 即:Rectangle.prototype.__proto__ === Object.prototype

// 打印出来看看,,
console.log(Rectangle.prototype.__proto__ === Object.prototype);
console.log(Object.prototype.isPrototypeOf(Rectangle));

在这里插入图片描述

第二点是,使用new操作符,如 p = new P();
等号左侧会有一个[[Prototype]]属性(浏览器中可以使用__proto__读取),指向P.prototype

// 于是,可以尝试将左侧的p改为一个自定义的构造函数,如下:

// 自定义Rectangle构造函数
function Rectangle(length, width) {
    this.length = length;
    this.width = width;
}

// 给Rectangle的原型添加一个getArea()方法
Recangle.prototype.getArea = function() {
    return this.length* this.width;
}

// Square构造函数
function Square(size) {
    this.length = size;
    this.width = size;
}

// Square继承Rectangle(实际上是是Square的原型对象指向构造函数Rectangle)
Square.prototype = new Rectangle();

var sq1 = new Square(2);
console.log(sq1.getArea());   // 4

// 执行sq1.getArea()方法时,JavaScript引擎实际上是按如下方式工作的:
// 首先在sq1中寻找getArea(),未找到
// 在顺着sq1的[[Prototype]]属性,找到sq1的原型Square.prototype,并在原型中查找,未找到
// 数着Square.prototype的[[Prototype]]属性找到其原型Rectangle.prototype,找到了..执行getArea()方法

所以继承的实质就是让,A的原型对象(A.prototype)成为另一个构造函数的实例,
就可以在A的实例中使用父元素的方法和属性了

参考《JavaScript面向对象精要》P72~P73

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值