call

  1. Function.prototype.myCall = function(){
  2. const fn = Symbol('fn');
  3. const [p, ...arg] = arguments;
  4. let undertake = p || window;
  5. undertake[fn] = this;
  6. const result = undertake[fn](...arg);
  7. delete undertake[fn];
  8. return result;
  9. }
  10. const o = {
  11. name:"张三"
  12. }
  13. function test(name){
  14. console.log(this, name)
  15. }
  16. test.myCall(o,'张三')

bind

  1. Function.prototype.myBind = function(){
  2. const fn = Symbol("fn")
  3. const [p, ...arg] = arguments;
  4. const _o = p || window;
  5. _o[fn] = this;
  6. return function(){
  7. const result = _o[fn](...[...arg, ...arguments]);
  8. delete _o[fn];
  9. return result;
  10. }
  11. }
  12. const o = {
  13. name:"张三"
  14. }
  15. function test(name,age){
  16. console.log(this, name, age)
  17. }
  18. let fn = test.myBind(o,'张三')(18)

apply

  1. Function.prototype.myApply = function(){
  2. const fn = Symbol('fn');
  3. const [p, arg] = arguments;
  4. const _o = p || window;
  5. _o[fn] = this;
  6. const result = _o[fn](...arg);
  7. delete _o[fn];
  8. return result;
  9. }
  10. const o = {
  11. sex:"0"
  12. }
  13. function test(name,age){
  14. console.log(this,name,age)
  15. }
  16. test.myApply(o,['zs',18])