bind返回的是一个函数,不会立即执行,需要手动触发

    1. // 实现bind方法
    2. Function.prototype.newBind = function (o) {
    3. if (typeof this != 'function') {
    4. throw new TypeError("error")
    5. }
    6. var that = this;
    7. var arr = Array.prototype.slice.call(arguments, 1)
    8. // 原型链 空函数桥接
    9. var bridgeF = function () { }
    10. newF = function () {
    11. // console.log(this instanceof newF);
    12. // console.log([...arguments]);
    13. // that.apply(o, [...arr, ...arguments])
    14. if (this instanceof bridgeF) {
    15. that.apply(this, [...arr, ...arguments])
    16. } else {
    17. that.apply(o, [...arr, ...arguments])
    18. }
    19. }
    20. bridgeF.prototype = that.prototype
    21. newF.prototype = new bridgeF
    22. return newF
    23. // return function () {
    24. // console.log([...arguments]);
    25. // that.apply(o, [...arr, ...arguments])
    26. // }
    27. }
    28. function person(a, b, c) {
    29. console.log(this.name);
    30. console.log("abc", a, b, c);
    31. }
    32. person.prototype.collection = "收藏"
    33. var obj = {
    34. name: "xiao"
    35. }
    36. // person.newBind(obj, "test", "aa")("xixi")
    37. var bibi = person.newBind(obj, "test", "aa")
    38. var b = new bibi("xixi")
    39. console.log("b.collection", b.collection);
    40. /*
    41. undefined
    42. newBind.js?9854:31 abc test aa xixi
    43. newBind.js?9854:42 b.collection 收藏
    44. */