Why object destructuring in javascript will affect scope?

I am trying to understand why object destructuring is changing the scope?

(function() {
    var o = {
        add: function(a , b) {
            return a + b;
        },
        log: function () {
            console.log(this);
        }
    }
    var { log } = o;
    o.log();
    log();
})();

this code will log two different objects

the first one is object o as expected but the second will log the global object

Answer

It’s not exactly right

function log() {
  console.log('na aahh')
}
(function() {
    var o = {
        add: function(a , b) {
            return a + b;
        },
        log: function () {
            console.log('hi, i am locally scoped');
        }
    }
    var { log } = o;
    o.log();
    log();
})();

Run and see.

But…when you log this it always takes on the nearest scope which happens to be global because its detached from the o when destructured.

Try doing something like this…

function log() {
  console.log('nananana')
}
(function() {
    var o = {
        add: function(a , b) {
            return a + b;
        },
        log: function () {
            console.log(this);
        }
    }
    o.log = o.log.bind(o);
    var { log } = o;
    o.log();
    log();
})();

and notice how it retains this on destructure.

Also… side note, you should use let over using var as let when declared also has block scope which is pretty nice.

Happy coding sir.