Skip to content

Instantly share code, notes, and snippets.

@SergeyLipko
Last active April 27, 2017 11:59
Show Gist options
  • Save SergeyLipko/20790a696eab43c7f78e898bf50d5639 to your computer and use it in GitHub Desktop.
Save SergeyLipko/20790a696eab43c7f78e898bf50d5639 to your computer and use it in GitHub Desktop.
/*
To learn this, you first have to learn what this is not, despite any assumptions or misconceptions that
may lead you down those paths. this is neither a reference to the function itself, nor is it a reference
to the function's lexical scope.
this is actually a binding that is made when a function is invoked, and what it references is determined
entirely by the call-site where the function is called.
*/
// * * * * * NOT Itself function * * * * *
function doSomth() {
// this никак не связывается с самой функцией
console.log(this.count); // this указывает не на функцию doSomth, а на контектс ее выполнения *
}
doSomth.count = 0;
doSomth(); // * this === undefind, this !== doSomth.count
// решение проблемы - принудительное связывание this с функцией
doSomth.call(doSomth); // <- закидываем контекст в функцию
// * * * * * NOT Scope * * * * *
function foo() {
var a = 2;
// this никаким образом не ссылается на Scope
// Scope вообще недоступен из кода, это чать движка JavaScript
// таким обзаром не следует пытаться связывать this со Scope
// так как это попросту невозможно в JavaScript
this.bar();
}
function bar() {
console.log(this.a);
}
foo(); // undefined
// * * * * * Implicit Binding * * * * *
function show() {
console.log(this.name);
}
const mark = {
name: 'Mark',
showName: show // записываем в ключ showName ссылку на функцию show
}
const dan = {
name: 'Dan',
showName: mark.showName // пробрасываем функцию сквозь объекты
}
const jack = {
name: 'Jack',
danReference: dan // записываем в ключ danReference ссылку на объект dan
}
// здесь видно, что функция вообще не привязывается к контексту
// он определяется исключительно во время выполнения функции
// -- this динамический --
dan.showName(); // Dan
jack.danReference.showName(); // Dan
// * * * * * Implicitly Lost * * * * *
function show() {
console.log(this.name);
}
const obj = {
name: 'Super',
show: show
}
const link = obj.show; // ссылка на функцию show, не связанная с объектом obj
link(); // undefined
function doShow(fn) {
// fn - такая же ссылка на саму функцию, не связанная с объектом
fn(); // undefined
}
doShow(obj.show);
// * * * * * Custom bind * * * * *
function foo(s) {
return this.a + s;
}
// стандартная запись
function _bind(fn, obj) {
return function() {
return fn.apply(obj, arguments);
}
}
// частичное применение из ФП
const _bindShortand = (fn, obj) => (...arg) => fn.apply(obj, arg);
const obj = {
a: 5
}
const hey = _bindShortand(foo, obj);
console.log(hey());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment