知识点
-
class 和继承
-
类型判断 instanceof
-
原型和原型链
1、如何准确判断一个变量是不是数组?
答:a instanceof Array
【类型判断 - instanceof】
xialuo instanceof Student // true
xialuo instanceof People // true
xialuo instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true
{} instanceof Object // true
// class 实际上是函数,可见是语法糖
typeof People // 'function'
typeof Student // 'function'
// 隐式原型和显示原型
console.log(xialuo.__proto__)
console.log(Student.prototype)
console.log(xialuo.__proto__ === Student.prototype)
2、class的原型本质,怎么理解?
-
原型和原型链的图示
-
属性和方法的执行规则
原型链图:
【如何用class实现继承】
- constructor
- 属性
- 方法
【继承】
- extends
- super
- 扩展或重写方法
// es6中class与继承
// 创建父类
class Parent{
constructor(name) {
this.name = name;
}
getName() {
console.log(this.name)
}
}
// 子类继承自父类
class Son extends Parent {
constructor(name,age) {
// super指向父类的实例对象,调用父类的constructor,必须先调用super方法,子类才能使用this
// this.age = age; // 子类继承父类的this对象并修改
super(name);
}
getName() {
// 调用父类的方法 console.log('son');
super.getName();
}
}
3、手写一个简易的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
}
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)
})
}
}
// 使用
let $p = new jQuery('p')
$p.each(elem => console.log(elem.nodeName)) // 3个P
$p.on('click',() => alert('clicked'))
$p.get(1) // <p>一段简易文字 2</p>
// 插件和扩展性
// 插件
jQuery.prototype.dialog = function(info) {
alert(info)
}
// “造轮子”
class myJQuery extends jQuery {
constructor(selector) {
super(selector)
}
// 扩展自己的方法
addClass(className) {
}
style(data) {
}
}
小结
- class和继承,结合上面手写jQuery的示例来理解
- instanceof
- 原型和原型链:图示 & 执行规则