Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active July 22, 2021 15:30
Show Gist options
  • Save wentout/772cd440094b23fcc91cf759eabc1c17 to your computer and use it in GitHub Desktop.
Save wentout/772cd440094b23fcc91cf759eabc1c17 to your computer and use it in GitHub Desktop.
testing destructuring assignment `this` patterns
// By James M Snell @jasnell
// the first tweet:
// https://twitter.com/jasnell/status/1385464365046894599?s=20
class F {
a = 1;
b() {
return this.a;
}
}
const { b } = new F;
try {
console.log(b());
} catch (error) {
console.error(error);
}
// the second tweet
// https://twitter.com/jasnell/status/1385464988798648321
class E {
a = 1;
get c() {
return () => {
return this.a;
}
}
}
const { c } = new E;
console.log('c :', c());
console.log('c.call :', c.call({ a: 2 }));
// preferred version then
// https://twitter.com/went_out/status/1385470268060180480
class G {
a = 1;
get d() {
const me = this;
return function () {
return (this || me).a;
}
}
}
const { d } = new G;
console.log('d :', d()); // 1
console.log('d.call :', d.call({ a: 2 })); // 2
// and seems this might also mean something important
// https://twitter.com/jasnell/status/1385549464912289792?s=20
const handler = function () {
const me = this;
return function () {
// we need strict here,
// as otherwise this will be
// a pointer to global!
'use strict';
const thisPointer = this || me;
if (thisPointer instanceof H) {
return thisPointer.a;
}
throw new TypeError('Value Access Denied!');
}
}
class H {
a = 1;
get e() {
return handler.call(this);
}
}
const h = new H;
const { e } = h;
console.log('e :', e()); // 1
try {
console.log('e.call 1st :');
e.call({ a: 2 });
} catch (error) {
console.error(error);
}
console.log('e.call 2nd :', e.call(h)); // 1
// step 5 : how do we do with multi inheritance!
class K {
a = 1;
get f() {
return handler.call(this);
}
}
const k = new K;
const { f } = k;
const multiProp = {
a: 3,
e,
f,
};
console.log('multi prop example\n\n\n');
try {
console.log('\nmultiProp.e');
multiProp.e();
} catch (error) {
console.log('as expected !');
console.error(error);
}
try {
console.log('\nmultiProp.f');
multiProp.f();
} catch (error) {
console.log('as expected !');
console.error(error);
}
console.log('\n');
console.log('and obvious thurther destructuring re-assignment ↓↓↓\n');
const {
e: x,
f: y,
} = multiProp;
debugger;
console.log('sure console.log(x()) works!');
console.log('as x is prop from instance of H');
console.log(x());
console.log('as expected !');
try {
console.log('\nbut y() does not!');
console.log('\nas y is prop from instanceof K');
debugger;
y();
} catch (error) {
console.log('!!!');
console.error(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment