面试-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 实现思路
-
DOM 选择器:首先需要一个选择 DOM 元素的能力,可以用类似
document.querySelectorAll()
的方式实现。 -
链式调用:jQuery 的最大特点之一是链式调用,即方法调用后返回同一个对象,因此可以继续调用其他方法。
-
插件机制:jQuery 提供了插件系统,让开发者可以通过扩展
$.fn
来添加新的功能。 -
扩展性:实现
$.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");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧