本期介绍原型、原型链和 class。包括 class ,继承,原型,原型链,instanceof。原型是 “JS 三座大山” 之一,原型和原型链也是必考知识点。
//语法结构
class 首字母大写 {
//构建
constructor(参数1,参数2){
}
}
class的本质仍然是函数(其实是ES6的语法糖)
es6的继承本质上是原型链 + 盗用构造函数
此原型图解可对照上面class 实现继承定义的类理解
原型链:
执行规则:
此原型链图解可对照上面class 实现继承定义的类理解
class People {
eat() {}
}
class Student extends People {
sayHi() {}
}
const xialuo = new Student(name, number);
// 实例对象隐式原型指向构造函数显式原型
xiaoluo.__proto__ === Student.prototype // true
Student.prototype.__proto__ === People.prototype // true
People.prototype.__proto__ === Object.prototype // true
// Object原型对象的隐式原型为null 所以null即原型链的顶端
Object.prototype.__proto__ === null // true
// 原型链
xiaoluo.__proto__ ->
Student.prototype.__proto__ ->
People.prototype.__proto__ ->
Object_prototype.__proto__ ->
null
instanceof:
使用instanceof/Array.isArray方法
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
}
// 插件
jQuery.prototype.dialog = function (info) {
alert(info)
}
// “造轮子”
class myJQuery extends jQuery {
constructor(selector) {
super(selector)
}
// 扩展自己的方法
addClass(className) {
}
style(data) {
}
}
// const $p = new jQuery('p')
// $p.get(1)
// $p.each((elem) => console.log(elem.nodeName))
// $p.on('click', () => alert('clicked'))
插件机制就是用 prototype 来对原型进行补充加强
造轮子就是用 extends 继承,然后新建自己的新方法
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有