zoukankan      html  css  js  c++  java
  • 通过一个例子程序来感受构造函数的继承

    有一构造函数如下:

     1 function Shape() {
     2   this.x = 0;
     3   this.y = 0;
     4 }
     5 
     6 Shape.prototype.move = function (x, y) {
     7   this.x += x;
     8   this.y += y;
     9   console.info('Shape moved.');
    10 };

    使用构造函数的主要目的就是创建实例对象,构造函数内部的this所关联的也是实例对象。

    另一个构造函数继承上述构造函数:

     1 // 第一步,子类继承父类的实例
     2 function Rectangle() {
     3   Shape.call(this); // 调用父类构造函数
     4 }
     5 // 另一种写法
     6 function Rectangle() {
     7   this.base = Shape;
     8   this.base();
     9 }
    10 
    11 // 第二步,子类继承父类的原型
    12 Rectangle.prototype = Object.create(Shape.prototype);
    13 Rectangle.prototype.constructor = Rectangle;
  • 相关阅读:
    React个人学习笔记
    electron 学习笔记
    微信小程序学习笔记
    算法
    17 django中间件
    16 django用户认证组件
    15 django_cookie&session
    14 django_forms
    13 django分页器
    12 django_ajax
  • 原文地址:https://www.cnblogs.com/flyover/p/14319155.html
Copyright © 2011-2022 走看看