1. 如何用class实现继承
// 父类
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(`姓名:${this.name},学号:${this.number}`)
}
}
class Teacher extends People{
constructor(name, major){
super(name)
this.major = major
}
teach(){
console.log(`${this.name} 教 ${this.major}`)
}
}
// 实例
const ll = new Student('李雷', 1234)
console.log(ll.name)
console.log(ll.number)
ll.sayHi()
ll.eat()
// 实例
const wanglaoshi = new Teacher('王老师', '语文')
console.log(wanglaoshi.name)
console.log(wanglaoshi.major)
wanglaoshi.teach()
wanglaoshi.eat()
效果
2. 类型判断 - instanceof
console.log(ll instanceof Student) // true
console.log(ll instanceof People) // true
console.log(ll instanceof Object) // true
console.log([] instanceof Array) // true
console.log([] instanceof Object) // true
console.log({} instanceof Object) // true
3. 原型
实例的隐式原型(__proto__
)指向构造函数的显示原型(prototype
)。
// class 实际上是函数,可见是语法糖
console.log(typeof People)
console.log(typeof Student)
// 隐式原型
console.log(ll.__proto__)
// 显示原型
console.log(Student.prototype)
console.log(ll.__proto__ === Student.prototype)
获取属性ll.name
或执行方法ll.sayHi()、ll.eat()
时,现在自身属性和方法中寻找,如ll.name
和ll.sayhi()
都在自身属性和方法。如果找不到,则自动去__proto__
中查找,如ll.eat()
。
4. 原型链
// 原型链
console.log(Student.prototype.__proto__)
console.log(People.prototype)
console.log(People.prototype === Student.prototype.__proto__)
5. 手写简易的jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写简易jQuery</title>
</head>
<body>
<div>一段文字 1</div>
<div>一段文字 2</div>
<div>一段文字 3</div>
<script>
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)
}
// 扩展自己的方法
addClass(className){
}
style(data){
}
}
</script>
</body>
</html>