手动实现bind
本文最后更新于:2023年3月19日 晚上
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 Function .prototype.myBind = function (context, ...args ) { const fn = this ; const bound = function (...args2 ) { const newArgs = [...args, ...args2]; if (this instanceof bound) { fn.apply(this , newArgs); } else { fn.apply(context, newArgs); } }; Object .setPrototypeOf(bound.prototype, fn.prototype); return bound; };function getName ( ) { console .log(this .name); console .log(...arguments); }function Person (name ) { this .name = name; } Person.prototype.getName = function ( ) { console .log(this .name); };let test = Person.myBind({}, 123 );let test2 = new test(789 ); test2.__proto__.getName = function ( ) { console .log("被篡改" ); }; Person.prototype.getName();