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__查找

  • 相关阅读:
    系统开机自动运行程序和自动启动服务
    Show/hide mouse cursor
    Trap mouse events outside of my application
    Delphi防止同时出现多个应用程序实例CreateMutex
    用Delphi实现抓屏
    .NET四种注释规范
    再谈C#里4个访问权限修饰符
    什么是组件以及为什么使用组件
    做项目的时候千万不能懒!
    范式篇之一范式理论
  • 原文地址:https://www.cnblogs.com/manhuai/p/14281967.html
Copyright © 2011-2022 走看看