Skip to content

Instantly share code, notes, and snippets.

@vladilenm
Created December 4, 2019 12:58
Show Gist options
  • Save vladilenm/fe0651f25949643a83940df6d00cca50 to your computer and use it in GitHub Desktop.
Save vladilenm/fe0651f25949643a83940df6d00cca50 to your computer and use it in GitHub Desktop.
const person = {
name: 'Владилен'
}
function info(phone, email) {
console.log(`Имя: ${this.name}, Тел.:${phone}, Email: ${email}`)
}
// Demo
// info.bind(person)('12345', 'v@mail.ru')
// info.bind(person, '12345')('v@mail.ru')
// info.bind(person, '12345', 'v@mail.ru')()
// 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', 'v@mail.ru')
bind(info, person, '12345')('v@mail.ru')
bind(info, person, '12345', 'v@mail.ru')()
// 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', 'c@mail.ru')
// 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', 'c@mail.ru'])
@nemiro
Copy link

nemiro commented Dec 5, 2019

or we can use a prototype to replace bind
info.prototype.bind = ..
or replace bind for all functions
Function.prototype.bind = ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment