Class和继承
class
class Student {
constructor(name, number) {
this.name = name;
this.number = number;
}
sayHi() {
console.log(
`Name:${this.name}, Id:${this.number}`
)
}
}
<!-- more -->
const Ricky = new Student("Ricky",100)
console.log(Ricky.name)
Ricky.sayHi()
//Ricky
//Name:Ricky, Number:100
继承
// 父类
class People {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eat something`);
}
}
// 子类
class Student extends People {
constructor(name, number) {
super(name);
this.number = number;
}
sayHi() {
console.log(`hi,${this.name},your number is ${this.number}`)
}
}
const me = new Student("RS",100)
me.sayHi()
me.eat()
hi,RS,your number is 100
RS eat something
类型判断
me instanceof Student // true
me instanceof People // true
me instanceof Object // true
typeof me // object
typeof Student // function
原型和原型链
原型
隐式原型和显示原型
每个class都有显示原型prototype
每个实例都有隐式原型_proto_
实例的_proto_指向对应class的prototype
me.__proto__ === Student.prototype //true
获取属性xialuo.name或执行方法xialuo.sayhi()时
先在自身属性和方法寻找
如果找不到则自动去_proto_中查找
原型链
如何准确判断一个变量是不是数组?
a instanceof Array
class的原型本质,怎么理解?
原型和原型链图示
属性和方法执行规则
手写一个简易的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);
});
}
}
// 插件
jQuery.prototype.dialog = function (info) {
alert(info);
};
// 造轮子
class myJquery extends jQuery {
constructor(selector) {
super(selector);
}
methods() {}
}