1. /**
    2. * 手写bind函数
    3. * bind返回fun的拷贝,并指定了fun的this指向,保存了fun的参数
    4. * 说白就是bind返回一个函数,函数内保存啦需要指定的this
    5. * @param {*} context
    6. * @param {...any} arg
    7. * @returns
    8. */
    9. Function.prototype.myBind = function (context, ...arg) {
    10. // 判断参数
    11. arg = arg ? arg : [];
    12. // 如果使用new的话 constructor会指向newFun
    13. // 应该指向调用bind()的函数
    14. // 以temp做为跳板, 毕竟现在this只是执行上下文
    15. const temp = function () {};
    16. // 由于bind 要返回一个函数, 先将this保存一下
    17. const fn = this;
    18. // 返回一个函数, 看之后要做什么
    19. const newFun = function (...newArg) {
    20. // 是不是要new 如果是使用new 那吗this 指向new出来的对象
    21. if (this instanceof temp) {
    22. return fn.apply(this, [...arg, ...newArg]);
    23. }
    24. // 没有使用new的情况 this 使用传递进来的this
    25. return fn.apply(context, [...arg, ...newArg]);
    26. };
    27. // 继承 防止new之后创建此对象的函数的引用为const newFun = function(){}
    28. temp.prototype = fn.prototype;
    29. // constructor 属性返回对创建此对象的函数的引用
    30. newFun.prototype = new temp();
    31. return newFun;
    32. };
    33. function show() {
    34. console.log(this);
    35. }
    36. var duyio = {
    37. x: 20,
    38. };
    39. var newSbow = show.newBind(duyio, 1, 2, 3);
    40. newSbow(5); //第二次参数 会将第一次的参数插入第二次参数的前面
    41. console.log(new newSbow().constructor); // 此处的函数引用是 show()
    42. //constructor 属性返回对创建此对象的 Boolean 函数的引用