zoukankan      html  css  js  c++  java
  • call,apply,bind实现

    call和apply都是对函数的直接调用,而bind方法返回的仍然是一个函数

    call的实现原理:在方法调用模式下,this 总是指向调用它所在方法的对象,this 的指向与所在方法的调用位置有关,而与方法的声明位置无关(箭头函数特殊)

    利用 this 的机制来实现 call

     1 Function.prototype.mycall = function(thisArg) {
     2     if(typeof this !== 'function') {
     3         throw TypeError(`${this} is not a function`);
     4     }
     5     const args = [...arguments].slice(1);
     6     thisArg = thisArg || window;
     7     thisArg.fn = this;
     8     const result = thisArg.fn(...args);
     9     delete thisArg.fn;
    10     return result;
    11 }

    apply的实现:

     1 Function.prototype.myapply = function(thisArg) {
     2     if(typeof this !== 'function') {
     3         throw TypeError(`${this} is not a function`);
     4     }
     5     thisArg = thisArg || window;
     6     const args = arguments[1];
     7     thisArg.fn = this;
     8     const result = thisArg.fn(...args);
     9     delete thisArg.fn;
    10     return result;
    11 }

    bind实现:封装了 call 的方法改变了 this 的指向并返回一个新的函数

    1 Function.prototype.mybind = function(fun) {
    2     if(typeof this !== 'function') {
    3         throw TypeError('Bind must be called on a function')
    4     }
    5     var self = this;
    6     return function () {
    7         self.apply(fun, arguments);
    8     }
    9 }
  • 相关阅读:
    网页字体设置你了解吗?
    CSS 定位 (Positioning)
    常用CSS缩写语法总结
    CSS 教程
    CSS Reset(CSS重置)
    边框模拟小三角形
    CSS sprites
    border:none和border:0的区别
    css display属性
    css的postion属性
  • 原文地址:https://www.cnblogs.com/vicky24k/p/11888962.html
Copyright © 2011-2022 走看看