系列文章目录
目录
前言
JS原型相关
一、class
// 类
class Student {
constructor(name, number) {
this.name = name;
this.number = number;
}
sayHi() {
console.log(`姓名 ${this.name},学号 ${this.number}`);
}
}
// 通过类 new 对象/实例
const cai = new Student('菜豆',100);
console.log(cai.name);
cai.sayHi();
二、继承
// 父类
class People {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eat apple`);
}
}
// 子类
class Student extents People {
constructor(name, number) {
super(name);
this.number = number;
}
sayHi() {
console.log(`姓名 ${this.name},学号 ${this.number}`);
}
}
const cai = new Student('菜豆',100);
cai.sayHi();
cai.eat();
三、类型判断-instanceof
cai instanceof Student // true
cai instanceof People // true
cai instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true
{} instanceof Object // true
原型关系
- 每个 class 都有显示原型 prototype
- 每个实例都有隐式原型 _proto_
- 实例的 _proto_ 指向对应 class 的 prototype
基于原型的执行规则
- 获取属性 cai.name 或执行方法 cai.sayHi() 时
- 先在自身属性和方法寻找
- 如果找不到则自动去 _proto_ 中查找
手写简易 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);
})
}
// 扩展...
}
<p>1</p>
<p>1</p>
<p>1</p>
const $p = new jQuery('p');
$p.get(1);
$p.each((elem) => console.log(elem.nodeName));
$p.on('click', () => alert('clicked'));
// 插件
jQuery.prototype.dialog = function (info) {
alert(info);
}
// "造轮子"
class myJQuery extends jQuery {
constructor(selector) {
super(selector);
}
// 扩展自己的方法
addClass(className) {
}
style(data){
}
}
总结
类、继承、instanceof,原型相关学习笔记。