Friday, May 29, 2020

this is new

Beware of sharing this.

Here's how to check if your this is new, or when you are accidentally using a shared this.

function Abbey() {
    this.name = 'you know my name';
    console.log('Abbey() called');
    this.jude = function () {
        console.log("Abbey's jude() called");
    }
}

Abbey.prototype.great = function () {
    console.log('great');
};


function jude() {
    console.log('root jude() called');
}


function hey() {
    console.log('Hey() called');
    try {
        this.jude();
    } catch (ex) {
        console.log("I'm not running in node/browser's REPL. Can't resolve this.jude()");
        console.log(ex);
    }
}


new Abbey();
hey();
console.log('\nthis is messy\n');
Abbey(); // forgot the new keyword
hey();


console.log('\n\nnew Abbey():');
// a's this is new. not shared this
var a = new Abbey();
console.log(a);
a.great();

Output:

dev@Developers-iMac % node y.js
Abbey() called
Hey() called
I'm not running in node/browser's REPL. Can't resolve this.jude()
TypeError: this.jude is not a function
    at hey (/Users/dev/Desktop/y.js:22:14)
    at Object. (/Users/dev/Desktop/y.js:31:1)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

this is messy

Abbey() called
Hey() called
Abbey's jude() called


new Abbey():
Abbey() called
Abbey { name: 'you know my name', jude: [Function] }
great

It's better to attach the instance's method to .prototype instead of attaching it to this. Aside from that it prevents accidentally using a shared this, it also unclutters the instance's data.

As seen from the output, the jude method become part of the data, whereas the great method doesn't.


The this can accidentally call other code when the code is run in node/browser's REPL. The following is the output of the same exact code above when it is run in REPL instead. Note that root jude is called.

No comments:

Post a Comment