Hiccup
发布于 2021-03-06 / 34 阅读
0
0

JavaScript-原型与原型链


原型

1.继承

问题:如何用class实现继承?

// 类
class Student {
    constructor(name, number) {
        this.name = name;
        this.number = number;
    }
    sayHi() {
        console.log(`姓名${this.name},学号${this.number}`);
    }
}

继承:

  • extends

  • super

  • 扩展或重写方法

// 父类
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}`);
    }
}

延申:Javascript继承的方式

2.instanceof 类型判断

var xialuo = new Student("夏洛", "100");
xialuo instanceof Student;  // true
xialuo instanceof People;   // true
xialuo instanceof Object;   // true
​
[] instanceof Array;    // true
[] instanceof Object;   // true
{} instanceof Object;   // true
typeof People; // function
// class 实际上是函数,可见是语法糖

2.原型

2.1.显示原型与隐式原型

// 隐式原型、显示原型
console.log(xialuo._proto_);
console.log(Student.prototype);
console.log(Student.prototype === xialuo._proto_);  // true
  • 每个class都有显示原型 prototype

  • 每个实例都有隐式原型 _proto_

  • 实例的 _proto_ 指向对应 classprototype

原型图示

2.2.基于原型的执行规则

  • 获取属性 xialuo.name 或执行方法 xialuo.sayHi() 时;

  • 先在自身属性和方法寻找;

  • 如果找不到则自动去 _proto_ 中查找;

xialuo.hasOwnProperty('name');  // true
xialuo.hasOwnProperty('sayHi'); // false

2.3.instanceof是基于原型链实现的

原型链图示

面试题

1.如何判断一个变量是不是数组

a instanceof Array;

2.class的原型本质

  • 原型和原型链的图示;

  • 属性和方法的执行规则;

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 < length; i++) {
            const elem = this[i];
            fn(elem);
        }
    }
    on(type, fn) {
        return this.each(elem => {
            elem.addEventListener(type, fn, false);
        });
    }
}
​
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);
}
$p.dialog('abc');
​
// 复写(造轮子)
class myJQuery extends jQuery {
    constructor(selector) {
        super(selector);
    }
    // 扩展自己的方法
    // ...
}



评论