ES5写法

  1. Function.prototype._bind = function () {
  2. if (typeof this !== "function") {
  3. throw new TypeError('Error')
  4. }
  5. let self = this
  6. let args = Array.prototype.slice.call(arguments, 1) //取出除第一个参数的所有参数
  7. let _this = arguments[0]
  8. return function () {
  9. return self.apply(_this, args)
  10. }
  11. }
  12. function fn() {
  13. this.a = arguments[0]
  14. console.log('a:' + this.a);
  15. console.log('name:' + this.name);
  16. }
  17. let obj = {
  18. name: 'zs'
  19. }
  20. console.log(fn._bind(obj, ['apply', '0', '1'])(1, 3));

ES6写法

  1. // ES6写法
  2. Function.prototype._bind = function (...args) {
  3. if (typeof this !== "function") {
  4. throw new TypeError('Error')
  5. }
  6. let self = this
  7. let context = args.shift() //shift 方法是将数组中的第一个数删除,然后然后返回删除的数
  8. return function (...arg) {
  9. console.log(args[0].concat([...arg]));
  10. return self.apply(context, args[0].concat([...arg]))
  11. }
  12. }
  13. function fn() {
  14. this.a = arguments[0]
  15. console.log('a:' + this.a);
  16. console.log('name:' + this.name);
  17. }
  18. let obj = {
  19. name: 'zs'
  20. }
  21. console.log(fn._bind(obj, ['apply', '0', '1'])(1, 3));