js常见原理面试题

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,141评论 1 32
  • 一、 JS面向对象编程 1、 面向对象介绍 什么是对象? Everything is object (万物皆对象)...
    宠辱不惊丶岁月静好阅读 849评论 0 2
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,306评论 0 3
  •   面向对象(Object-Oriented,OO)的语言有一个标志,那就是它们都有类的概念,而通过类可以创建任意...
    霜天晓阅读 2,139评论 0 6
  • (原创首发,不得转载) 夏至翩翩来,夫妻约草忙。 遥望菩提树,幸福绵又长。
    财道阅读 628评论 0 12