zoukankan      html  css  js  c++  java
  • 隐式绑定和显式绑定实现一个apply

    apply作用是改变this的指向。在js中有两种方式改变this的指向。一种是显式的也就是apply、call和bind;另外一种就是隐式的。

    因此手动实现apply也就至少有两种方法。

    利用隐式绑定。

            Function.prototype.myapply1 = function(target, args){
               if(typeof args === 'undefined' || args === null) {
                   args = []
               }
               if(typeof target === 'undefined' || target === null) {
                   target = window
               }
    
               target = new Object(target)
    
               const targetkey = 'targetkey'
               target[targetkey] = this
               const result = target[targetkey](...args) // 借助隐式绑定实现this执行改写
               delete target[targetkey]
               return result
            }
    

      利用显式绑定,借助call或者bind

    // 利用显示绑定 借助call
            Function.prototype.myapply2 = function(target, args){
                if(typeof args === 'undefined' || args === null) {
                   args = []
               }
               if(typeof target === 'undefined' || target === null) {
                   target = window
               }
               const result = this.call(target, ...args)
               return result
            }
    

      

    我站在山顶看风景!下面是我的家乡!
  • 相关阅读:
    2021年2月22
    2021年2月21
    2021年2月20
    2021年2月19
    动态添加titie属性
    根据内容改变文字颜色!
    自定义弹出层!
    来回切换图标以及文字
    20180831xlVBA_WorksheetsCosolidate
    20180830xlVBA_合并计算
  • 原文地址:https://www.cnblogs.com/zhensg123/p/14732626.html
Copyright © 2011-2022 走看看