面试-JS基础知识-原型和原型链

JS本身是基于原型来继承的语言。
问题引出:

  • 如何判断一个变量是不是数组?
  • 手写一个简易的jQuery,考虑插件和扩展性
  • class的原型本质,怎么理解?

知识点

  • class和继承
  • 类型判断 instanceof
  • 原型和原型链

class
class相当于一个模版,可以用来构建(constructor)东西。

class Student {
  constructor(name, number){
    this.name = name
    this.number = number
  }
  sayHi(){
    console.log(
      `name ${this.name}, number ${this.number}`
    )
  }
}

// 通过类 new一个实例或对象
const taylor = new Student('Tay',100)
console.log(taylor.name)
console.log(taylor.number)
taylor.sayHi()

继承

  • extends(子类继承父类)
  • super (子类执行父类的构造函数)
  • 扩展或重写方法
class People {
  constructor(name) {
    this.name = name;
  }
  eat() {
    console.log(`${this.name} likes to eat delicious food!`);
  }
}

// 子类
class Student extends People {
  constructor(name, studentNum) {
    super(name);
    this.studentNum = studentNum;
  }
  sayHi() {
    console.log(`I am ${this.name}, my student number is ${this.studentNum}.`);
  }
}

const xialuo = new Student('夏洛',0001)
xialuo.sayHi()

原型


原型链
当前对象会先从自身寻找有无该属性,没有的话就顺着原型链的隐式原型一层一层往上找,直到找到为止。

手写建议jQuery,考虑插件和扩展性
简易 jQuery 实现思路

  1. DOM 选择器:首先需要一个选择 DOM 元素的能力,可以用类似 document.querySelectorAll() 的方式实现。

  2. 链式调用:jQuery 的最大特点之一是链式调用,即方法调用后返回同一个对象,因此可以继续调用其他方法。

  3. 插件机制:jQuery 提供了插件系统,让开发者可以通过扩展 $.fn 来添加新的功能。

  4. 扩展性:实现 $.extend() 方法,用于扩展 jQuery 对象或插件。

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(fn) {
    for (let i = 0; i < this.length; i++) {
      const elem = this[i];
      fn(elem);
    }
  }

  on(type, fn) {
    return this.each((elem) => {
      elem.addEventListener(type, fn, false);
    });
  }
}

// 扩展DOM API,使用普通函数以正确使用 `this`
jQuery.prototype.dialog = function(info) {
  alert(info);
};

// 继承扩展
class myJQuery extends jQuery {
  constructor(selector) {
    super(selector);
  }

  // 添加一个类
  addClass(className) {
    return this.each((elem) => {
      elem.classList.add(className);
    });
  }

  // 设置样式
  style(property, value) {
    return this.each((elem) => {
      elem.style[property] = value;
    });
  }
}

// 使用示例
const $p = new jQuery("p");
$p.get(1);
$p.each((elem) => console.log(elem.nodeName));
$p.on("click", () => alert("clicked"));

// 使用 myJQuery 扩展的功能
const $div = new myJQuery("div");
$div.addClass("my-class");
$div.style("color", "red");
$div.dialog("This is a dialog box");
posted @   一个甜橙子  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示