Js手动实现call和apply方法

更新日期: 2019-08-18阅读: 1.8k标签: 方法

call实现

语法

fun.call(thisArg, arg1, arg2, ...)

参数:

thisArg:在 fun 函数运行时指定的 this 值。

if(thisArg == undefined|null) this = window,if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()

arg1, arg2, ...指定的参数列表。

Function.prototype.call2 = function (thisArg) {
    if (thisArg === undefined || thisArg === null) {
        thisArg = window;
    } else {
        switch (typeof thisArg) {
            case 'number':
                thisArg = new Number();
                break;
            case 'boolean':
                thisArg = new Boolean();
                break;
            case 'string':
                thisArg = new String();
                break;
        }
    }

    thisArg.fn = this;

    let result;
    if (arguments.length <= 1) {
        result = thisArg.fn();
    } else {
        let args = [];
        for (let i = 1; i < arguments.length; i++) {
            args.push('arguments[' + i + ']');
        }
    
        result = eval(`thisArg.fn(${args})`)
    }

    delete thisArg.fn;
    return result;
}

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call2(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call2(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
console.log('cheese: ', cheese);
var fun = new Toy('robot', 40);
console.log('fun: ', fun);


apply实现

语法:

func.apply(thisArg, [argsArray])

参数:

thisArg:可选的。在 func 函数运行时使用的 this 值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动替换为指向全局对象,原始值会被包装。

argsArray:可选的。一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 func 函数。如果该参数的值为 null 或 undefined,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。 浏览器兼容性 请参阅本文底部内容。

Function.prototype.apply2 = function (thisArg, argsArray) {
    thisArg = thisArg || window;
    thisArg.fn = this;

    let result;
    if (!argsArray) {
        result = context.fn();
    } else {
        var tempArgs = [];
        for (var i = 0, len = argsArray.length; i < len; i++) {
            tempArgs.push('args[' + i + ']');
        }
        result = eval(`thisArg.fn(${tempArgs})`)
    }
    
    delete thisArg.fn;
    return result;
}

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.apply2(this, [name, price]);
  this.category = 'food';
}

function Toy(name, price) {
  Product.apply2(this, [name, price]);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
console.log('cheese: ', cheese);
var fun = new Toy('robot', 40);
console.log('fun: ', fun);


总结

实现难点:

  1. 需要考虑传入的thisArg的多种类型
  2. 将函数设置成thisArg的属性,来实现this的绑定,调用完成后需要delete该属性
  3. 使用eval来实现需要传参给该函数的情况

链接: https://www.fly63.com/article/detial/5365

html/css解决inline-block内联元素间隙的多种方法总汇

inline-blcok元素中间的空白符引起的间隙,处理方法总结包括:改变书写结构、使用font-size:0、使用margin负值、使用letter-spacing或word-spacing、丢失结束标签、W3C推荐 导航方法(兼容IE6等)、YUI的inline-block间隙处理等...

JS实现碰撞检测的方法分析

本文实例讲述了JS实现碰撞检测的方法。分享给大家供大家参考,具体如下:一个简单的碰撞检测例子,检测div1是否和div2发生碰撞,当div1碰到div2时,改变div2的颜色

css实现左右两边竖条的多种方法总结

css实现边竖条的多种方式:border、使用伪元素、外 box-shadow、内 box-shadow、drop-shadow、渐变 linearGradient、轮廓 outline、滚动条

js中math方法_整理js中常用的math方法总结

记录下与Math有关的常用方法,如:求最大值、最小值等,或者是保留几位数啥的。本文主要介绍了JavaScript中Math对象的方法,具有一定的参考价值,下面跟着小编一起来看下吧

js中split,splice,slice方法之间的差异_splice()、slice()、split()函数的区分

Split是切割字符串的一种方法,该方法主要用于把一个字符串分割成字符串数组。splice()方法向/从数组中添加/删除元素,然后返回被删除的元素组成的数组。slice()方法主要用于截取数组,并返回截取到的新数组。

JS获取当前时间戳的方法

第一种:获取的时间戳是把毫秒改成000显示,因为这种方式只精确到秒,第二种和第三种是获取了当前毫秒的时间戳。

js 实现二级联动

在web开发中我们经常会遇到页面的一个二级联动技术,二级联动字面解释就是说我在选择一级select不同的option,下面的二级option的属性值在进行相应的变化。

常用原生JS方法总结(兼容性写法)

经常会用到原生JS来写前端。。。但是原生JS的一些方法在适应各个浏览器的时候写法有的也不怎么一样的,一下的方法都是包裹在一个EventUtil对象里面的,直接采用对象字面量定义方法了

js 操作剪贴板

是通过 js 操作 textarea input 输入框,只能操作输入框,不能操作其它元素。所有的 复制/剪切/粘贴 都是要在选中输入框中的文本之后,才进行操作的。

js async的常用方法

async函数是Generator 函数的语法糖,async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已。async函数对Generator 函数的改进点有以下几点:

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!