企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## call 思路: 1. 在call的第一个参数上添加一个方法 2. 执行这个方法并传参 3. 删除这个方法 ``` const persion = { name: 'tom', say: function(age) { console.log('hello', this.name) console.log('hello', age) } } const persion1 = { name: 'jerry' } Function.prototype.myCall = function(context) { // 思路是往context上添加say方法 context = context || global context.fun = this let args = [...arguments].slice(1) context.fun(...args) delete context.fun console.log(context) } persion.say.myCall(persion1, '18') // hello jerry // hello 18 // { name: 'jerry' } ``` ## apply (参数可以直接传入 arguments) ``` Function.prototype.myApply = function(context) { context = context || global context.fn = this const res = arguments[1] ? context.fn(...arguments[1]) : context.fn() delete context.fn return res } persion.say.myApply(persion1, [18, 19, 20]) ``` ## bind 1. 返回一个新函数 2. bind的第一个参数是新函数调用时的this值 3. bind的第二个参数是新函数的参数 4. bind 返回的结果是function,当被new调用时,bind的第一个参数无效( **因为 new调用时,绑定this的优先级高于bind,所以bind绑定的无效**) ``` function Person(name, age) { this.name = name; this.age = age; } var _Person = Person.bind({name: 'lalala', age: 18}); var p = new _Person('hanzichi', 30) // {name: "hanzichi", age: 30} ``` ### 手写bind ``` Function.prototype.myBind = function(context) { if(typeof this !== 'function'){ throw new TypeError('lallal') } const self = this const args = [...arguments].slice(1) const bound = function() { const allArgs = args.concat([...arguments]) if(this instanceof bound){ const result = self.apply(this, allArgs) if(result && (typeof result === 'function' || typeof result === 'object')){ return result } return this } return self.apply(context, allArgs) } return bound } ```