zoukankan      html  css  js  c++  java
  • 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__查找

  • 相关阅读:
    浏览器缓存
    FLINK --- 写HDFS
    ArrayList 线程不安全
    rocketMQ源码之 似乎并不能严格进行顺序消费
    报错 Aray size is not a small enough positive integer 的解决方案
    什么是函数的柯里化?
    props, state与render函数关系 – 数据和页面是如何实现互相联动的?
    【自我管理】my schedule
    【解题报告】洛谷P1219 八皇后
    【解题报告】洛谷P1433 吃奶酪
  • 原文地址:https://www.cnblogs.com/manhuai/p/14281967.html
Copyright © 2011-2022 走看看