首页 > 试题广场 >

修改 this 指向

[编程题]修改 this 指向
  • 热度指数:117434 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
封装函数 f,使 f 的 this 指向指定的对象
示例1

输入

输出

推荐
function bindThis(func, oTarget) {
    return function(){
        return func.apply(oTarget, arguments);
    };
}

function bindThis(f, oTarget) {
return  f.bind(oTarget);
}
两种方法都可以
编辑于 2016-03-23 10:54:52 回复(17)
主要考点:
1.this作用域
2.call apply bind的理解
3.argument的理解
4.展开语法...的理解
return function() {
      console.log('arguments', arguments);
        return f.call(oTarget, ...arguments);
    }
发表于 2021-07-04 21:41:29 回复(0)
function bindThis(f, oTarget) {
   return f.bind(oTarget)
}
发表于 2021-06-17 20:57:34 回复(0)
function bindThis(f, oTarget) {
    return function () {
        return f.apply(oTarget, arguments)
    }
}

匿名函数是因为call apply是立即执行的,而bind是返回一个改变上下文的函数副本
发表于 2021-06-09 10:23:52 回复(0)
  function bindThis(f, oTarget) {
    return f.bind(oTarget);
  }

发表于 2021-03-31 14:27:03 回复(0)
function bindThis(f, oTarget) {
    return function(){
        return f.call(oTarget, ...arguments);
    }
}

修改this指针的3个方法, call, apply, bind. 3者均可

发表于 2021-03-23 14:51:22 回复(0)
function bindThis(f, oTarget) {
    return f.bind(oTarget);
}


发表于 2021-03-11 14:32:35 回复(0)
function bindThis(f, oTarget) {
    var temp = Symbol()
    oTarget[temp] = f
    return function (...params) {
        return oTarget[temp](...params)
    }
}
原来大家都直接用了 call...我还以为考察点是手写call 尴尬
发表于 2021-02-04 11:10:27 回复(0)
bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()第一个参数的值,例如,f.bind(obj),实际上可以理解为obj.f(),这时,f函数体内的this自然指向的是obj
发表于 2021-01-22 14:28:09 回复(0)
// apply
function bindThis(f, oTarget) {
  return function() {
    return f.apply(oTarget, arguments);
  }
}

// call
function bindThis(f, oTarget) {
  return function() {
    return f.call(oTarget, ...arguments);
  }
}

// bind
function bindThis(f, oTarget) {
  return f.bind(oTarget);
}
没有提词器不觉得很扯吗?

发表于 2021-01-06 11:38:19 回复(0)
function bindThis(f, oTarget) {
    return f.bind?f.bind(oTarget):function(){return f.apply(oTarget,arguments)}
}
如果有bind函数直接调用,没有调用call和apply函数进行绑定,因为立即调用缘故采用匿名函数封装,call写法:
function bindThis(f, oTarget) {
    return f.bind?f.bind(oTarget):function(){return f.apply(oTarget,..arguments)}
}

发表于 2020-10-25 22:00:41 回复(0)
请问,为什么这么写不行呢?
function bindThis(func, oTarget) {
        return func.apply(oTarget);
}

发表于 2020-07-09 20:01:10 回复(1)

问题信息

难度:
11条回答 25914浏览

热门推荐

通过挑战的用户

查看代码