Created
December 4, 2019 12:58
-
-
Save vladilenm/fe0651f25949643a83940df6d00cca50 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const person = { | |
name: 'Владилен' | |
} | |
function info(phone, email) { | |
console.log(`Имя: ${this.name}, Тел.:${phone}, Email: ${email}`) | |
} | |
// Demo | |
// info.bind(person)('12345', '[email protected]') | |
// info.bind(person, '12345')('[email protected]') | |
// info.bind(person, '12345', '[email protected]')() | |
// 1 Простой | |
// function bind(fn, context, ...rest) { | |
// return fn.bind(context, ...rest) | |
// } | |
// 2 Без встроенных методов | |
// function bind(fn, context, ...rest) { | |
// return function(...args) { | |
// const uniqId = Date.now().toString() | |
// | |
// context[uniqId] = fn | |
// | |
// const result = context[uniqId](...rest.concat(args)) | |
// | |
// delete context[uniqId] | |
// | |
// return result | |
// } | |
// } | |
// 3 ES5 | |
// function bind(fn, context) { | |
// const rest = Array.prototype.slice.call(arguments, 2) | |
// return function() { | |
// const args = Array.prototype.slice.call(arguments) | |
// return fn.apply(context, rest.concat(args)) | |
// } | |
// } | |
// 4 ES6 | |
function bind(fn, context, ...rest) { | |
return function(...args) { | |
// return fn.apply(context, rest.concat(args)) | |
return fn.call(context, ...rest.concat(args)) | |
} | |
} | |
bind(info, person)('12345', '[email protected]') | |
bind(info, person, '12345')('[email protected]') | |
bind(info, person, '12345', '[email protected]')() | |
// Call | |
function call(fn, context, ...args) { | |
const uniqId = Date.now().toString() | |
context[uniqId] = fn | |
const result = context[uniqId](...args) | |
delete context[uniqId] | |
return result | |
} | |
// call(info, person, '1234', '[email protected]') | |
// Apply | |
function apply(fn, context, args) { | |
const uniqId = Date.now().toString() | |
context[uniqId] = fn | |
const result = context[uniqId](...args) | |
delete context[uniqId] | |
return result | |
} | |
apply(info, person, ['1234', '[email protected]']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or we can use a prototype to replace bind
info.prototype.bind = ..
or replace bind for all functions
Function.prototype.bind = ..