美文网首页面试那些事
手写js中改变this的三种方法

手写js中改变this的三种方法

作者: _静夜听雨_ | 来源:发表于2021-11-24 09:34 被阅读0次

在es6之前,我们经常遇到需要手动改变this指向的问题,call? apply?bind?,三者有啥区别,搞懂原理,也就清晰了。

call

Function.prototype.my_call = function(obj, ...args){
    obj = obj || window;
    const fn = Symbol();// Symbol防止重名key
    obj[fn] = this;
    return obj[fn](...args);// 执行,返回执行值
}

apply

Function.prototype.my_apply = function(obj, args){
    obj = obj || window;
    const fn = Symbol();// Symbol防止重名key
    obj[fn] = this;
    return obj[fn](...args);// 执行,返回执行值
}

bind

Function.prototype.my_bind = function(obj, ...args){
    obj = obj || window;
    const fn = Symbol();// Symbol防止重名key
    obj[fn] = this;
    const _this = this;//保存this
    const res = function(...args1){
        if(this instanceof _this){
            this[fn] = _this;
            this[fn](...[...args, ...args1]);
            delete this[fn];
        }else{
            this[fn](...[...args, ...args1]);
            delete this[fn];
        }
    }
    res.prototype = Object.create(this.prototype);
    return res;
}

相关文章

  • JS初始化

    js中初始化常用的三种方法: //方法一:(jQuery)$(document).ready(function()...

  • 手写js数组中的reduce方法

    定义和用法 ​ reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一...

  • DOM的事件绑定、事件监听

    JS有三种常用的绑定事件的方法 在DOM元素上直接绑定 在JS代码中绑定 在JS中绑定事件监听函数 在DOM中直接...

  • 2-webpack4.x打包图片三大方法

    三种方法: 一、在js 中创建图片来引入二、在css中引入background('url')三、 1.在js创建图...

  • 第二章 在html中使用js

    1在html 中的使用js有三种方法 1.1 在html 用script 标签直接把js代码加到html文件中 1...

  • js 数组

    js 中数组的长度发生改变,数组就真的发生改变,快速清空数组就让数组长度为0js 数组的方法

  • JavaScript中apply、call和bind的区别

    js中改变this指向的方式主要有三种:apply、call和bind 相同点:都是用来改变函数的this对象的指...

  • Node.js 中使用 ES6 中的 import / exp

    Node.js 中使用 ES6 中的 import / export 的方法大全 三种方法。先上图。 源代码文件...

  • 封装call,apply,bind方法

    众所周知,call,apply,bind三种方法,都可以改变this的指向,区别只在于传参的不同,今天来用原生js...

  • JS_bind

    前言 bind、call、apply 三个改变指向函数,在JS面试中,经常问道。本文收录了 四种 手写bind的方...

网友评论

    本文标题:手写js中改变this的三种方法

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