Js手动实现call和apply方法

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

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://fly63.com/article/detial/5365

相关推荐

js返回上一页的实现方法

下面是常用代码:如果是用按钮做的话就是:用图片做的话就是:[color=#FF0000]几秒钟后[/color]自动返回上一页代码:(加入两个head间,3000表示3秒)

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

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

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

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

JS获取当前时间戳的方法

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

js async的常用方法

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

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

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

前端js常用方法封装

输入一个值,返回其数据类型;数组去重;字符串去重;深拷贝 浅拷贝;reverse底层原理和扩展;圣杯模式的继承;找出字符串中第一次只出现一次的字母;找元素的第n级父元素

在一个JS文件中引用另一个JS文件的方法

在调用文件的顶部加入下例代码:document.write;我们可以在某个html中引用了你需要的js文件,我们可以通过拿到那个html文件的对象,然后在通过这个对象去引用js的方法。

js中Element.getBoundingClientRect()方法

Element.getBoundingClientRect()方法返回元素的大小及其相对于视口的位置。返回值是一个 DOMRect 对象,这个对象是由该元素的 getClientRects() 方法返回的一组矩形的集合, 即:是与该元素相关的CSS 边框集合

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

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

点击更多...

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