为什么 javascript 中的对象解构会影响作用域?

Why object destructuring in javascript will affect scope?

我想了解为什么对象解构会改变范围?

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

此代码将记录两个不同的对象

第一个是预期的对象 o 但第二个将记录全局对象

更新(2021 年 5 月 3 日): 如果您有同样的问题并正在寻找更详细的答案,请同时阅读以下内容: How does the "this" keyword work?

不完全正确

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();
})();

运行 看看。

但是...当您记录 this 时,它总是采用最近的范围,恰好是全局范围,因为它在解构时与 o 分离。

尝试做这样的事情...

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();
})();

并注意它如何在解构时保留 this

另外...边注,您应该使用 let 而不是使用 var 因为 let 当声明时也有非常好的块作用域。

编码愉快,先生。

你所做的或多或少等同于

const log = o.log

您已经从一个对象中提取了一个方法,但是试图在不做任何其他事情的情况下调用它,this将不会引用原始对象。你需要 bind 它。

const log = o.log.bind(o)

这取决于您将 this 设置为:

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