bind-demo.js 460 B

1234567891011121314151617181920212223242526
  1. const obj = {
  2. name: 'yibo'
  3. }
  4. function fn(a, b) {
  5. console.log(this)
  6. console.log(a + b)
  7. return a + b
  8. }
  9. function myBind(obj) {
  10. const context = this
  11. const newArguments = Array.prototype.slice.call(arguments)
  12. newArguments.shift()
  13. return function () {
  14. return context.apply(obj, newArguments)
  15. }
  16. }
  17. const res = fn(1, 2)
  18. console.log(res)
  19. Function.prototype.myBind = myBind
  20. const myFn = fn.myBind(obj, 5, 8)
  21. const res2 = myFn()
  22. console.log(res2)