美文网首页
js常见原理面试题

js常见原理面试题

作者: 一现_ | 来源:发表于2019-07-30 18:24 被阅读0次

1. 实现一个call函数

// 将要改变this指向的方法挂到目标this上执行并返回

Function.prototype.call = function(context) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    context = context || window
    context.fn = this
    let arg = [...arguments].slice(1)
    let result = context.fn(...arg)
    delete context.fn
    return result 
}

2. 实现一个apply函数

Function.prototype.apply = function(contex) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    context = context || window
    context.fn = this
    let result 
    if(argument[1]) {
        result = context.fn(...argument[1])
    } else {
        result = context.fn()
    }
    delete context.fn
    return result
}

3. 实现一个bind函数

Function.prototype.bind = function(context) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    let _this = this
    let arg = [...arguments].slice(1)
    // 处理使用 new 的情况
    return function F(){
        if(this instanceof F) {
            return new _this(...arg, ...arguments)
        } else {
            return _this.apply(context, arg.concat(...arguments))
        }
    }
}

4. instanceof原理

A instanceof B 用于判断 A 的原型链中是否有 B 的存在,相当于右边 B 的变量原型是否在左边 A 的原型链上

// 右边变量的原型存在于左边变量的原型链上
function instanceof(left, right) {
    let leftValue = left.__proto__
    let rightValue = right.prototype
    // 循环查找,找到返回
    while (true) {
        if(leftValue === null) {
            return false
        }
        if(leftValue === rightValue) {
            return true
        }
        leftValue = leftValue.__proto__
    }
}

5. Object.create 原理

create 创建一个空对象,将传入的参数作为创建后对象的原型

function create(obj) {
    function F(){}
    F.prototype = obj
    return new F()
}

6. new 本质

new 是可以进行调用构造函数的 constructor

function

相关文章

网友评论

      本文标题:js常见原理面试题

      本文链接:https://www.haomeiwen.com/subject/oxhorctx.html