Skip to content
On this page

原型和原型链

类型判断-instanceof

js
//xialuo Student的实例,Student类继承People类 
xialuo instanceof Student  // true
xialuo instanceof People  // true
xialuo instanceof Object  // true

[] instanceof Array  // true
[] instanceof Object  // true
{} instanceof Object  // true

原型

js
// class 实际上是函数,是构造函数的语法糖
typeof People  // function
typeof Object  // function

//隐式原型和显示原型
xialuo.__proto__
Student.prototype
xialuo.__proto__ === Student.prototype

image-20230304222045940

  • 原型关系
    • 每个class都有显示原型 prototype
    • 每个实例都有隐式原型 __ proto__
    • 实例的__ proto__指向对应的class的prototype
  • 基于原型的执行规则
    • 获取属性或执行方法时,先在自身属性和方法里找
    • 如果找不到则去__ proto__中查找

原型链

js
People.prototype === Student.prototype.__proto__

image-20230304222045940

js
xiaoluo.hasOwnProperty('name') //true
xiaoluo.hasOwnProperty('sayHi') //false
xiaoluo.hasOwnProperty('eat') //fslae
xiaoluo.hasOwnProperty('hasOwnProperty') //false

image-20230304222045940

  • 提示
    • class是ES6语法规范,有ECMA委员会发布
    • ECMA只规定语法规则,即书写规范,不规定如何实现
    • 以上实现都是基于V8引擎实现

手写简易JQuery

js
class JQuery {
  constructor(selector) {
    const result = document.querySelectorAll(selector);
    const length = result.length;
    for (let i = 0; i < length; i++) {
      this[i] = result[i];
    }
    this.length = length;
    this.selector = selector;
  }

  get(index) {
    return this[index];
  }

  each(fun) {
    for (let i = 0; i < this.length; i++) {
      fun(this[i]);
    }
  }

  on(type, fun) {
    return this.each((ele) => {
      ele.addEventListener(type, fun, false);
    });
  }
  // 可扩展更过API
}

// 扩展
JQuery.prototype.dialog = function(info){
  alert(info)
}
// 造轮子
class SurperJQuery extends JQuery{
  constructor(selector){
    super(selector)
  }
  // 扩展自己的API
}