文章
2025年10月28日
JS 基础-原型和原型链

JS 基础-原型和原型链

理解 JS 原型(显示原型和隐式原型),用class实现继承

如何用 class 实现继承

class name {
  // 类体
}

class name extends otherName {
  // 类体
}

简单的类声明

super() 只能在 constructor 中使用,并且必须在使用 this 之前调用

class Rectange {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  
  getArea() {
    return this.width * this.height;
  }
}

class FilledRectange extends Rectange {
  constructor(width, height, color) {
    super(width, height);
    this.color = color;
  }
}

const rect = new FilledRectange(10, 20, #f2f2f2);

如何理解 JS 原型(隐式原型和显示原型)

console.log(rect.__proto__ === FilledRectange.prototype) // true

原型关系

  • 每个构造函数(class)都有显示原型 prototype
  • 每个实例都有隐式原型 __proto__
  • 实例 rect 的隐式原型 __proto__ 指向构造函数 FilledRectange 的显示原型 prototype
  • 原型链的顶端是 Object.prototype

原型链(基于原型的执行规则)

  • 获取属性或者执行方法时
  • 先在自身属性和方法查找
  • 找不到则自动沿着 __proto__ 查找,直到 null 终止

问题解答

如何准确判断一个变量是数组

  • arr instanceof Array
  • Object.prototype.toString.call(arr) === 'object Array'
© 2025-present Tszkong Cheng. All Rights Reserved.