js面试题-原型和原型链

__proto__:隐式原型,prototype:显示原型,二者全等(===)

原型链是用来查找引用类型的属性方法的。

要查找某个属性方法时,从当前位置开始,沿着原型链一级一级向上查找,找到了就执行对应操作;否则,继续查找,直到Object.prototype.proto,为 null。

原型关系

  • 每个class都有显示原型prototype

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

  • 实例__proto__指向对应class的prototype

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

使用 instanceof Array

2.手写一个简易的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]
            console.log(result)
        }
        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)
        })
    }
    // 扩展很多 DOM API
}

// 插件
jQuery.prototype.dialog = function (info) {
    alert(info)
}

// “造轮子”
class myJQuery extends jQuery {
    constructor(selector) {
        super(selector)
    }
    // 扩展自己的方法
    addClass(className) {

    }
    style(data) {
        
    }
}

// const $p = new jQuery('p')
// $p.get(1)
// $p.each((elem) => console.log(elem.nodeName))
// $p.on('click', () => alert('clicked'))

3.class的原型本质,怎么理解

class 实际上是函数,可见class是语法糖。

  • 获取属性xialuo.name或执行方法xialuo.sayhi时

  • 现在自身属性和方法寻找

  • 如果找不到自动去__proto__查找

原文地址:https://www.cnblogs.com/manhuai/p/14281967.html