【发布时间】:2021-07-13 05:38:24
【问题描述】:
我无法准确理解为什么 this 在某些情况下具有价值,而在其他情况下则没有。我维护了一个库,为了解释我的困惑,它被精简到最低限度,如下所示:
const arrayify = f => {
console.log('init', f.name, !!this);
return function (thingOrThings, ...args) {
console.log('arrayify for ', f.name, !!this);
return [thingOrThings].map(t => f.call(this, t, ...args));
};
};
class Utils {}
Object.assign(Utils.prototype, {
setProperty: arrayify(function setPropertyFunc(layer, prop, value) {
console.log('setPropertyFunc called', !!this); // outputs true
}),
hoverPopup(layers, cb, popupOptions = {}) {
console.log('hoverPopup init', !!this);
arrayify(function hoverPopupFunc(layer, cb) {
console.log('hoverPopupFunc called', !!this); // outputs false
})(layers, cb);
},
});
(它看起来过于复杂,因为我删除了所有实际有用的东西。但基本上arrayify 允许函数采用单个事物或事物数组,并隐式运行在数组中的每个项目上后一种情况。)
我这样称呼它:
const U = new Utils();
U.setProperty('mylayer', 'lineColor', 'red');
U.hoverPopup('mylayer', () => 1);
输出:
init setPropertyFunc false
arrayify for setPropertyFunc true
setPropertyFunc called true
hoverPopup init true
init hoverPopupFunc false
arrayify for hoverPopupFunc false
hoverPopupFunc called false
所以在第一种情况下,调用U.setProperty 调用arrayify,并且this(在arrayify 内部)有一个值。同样this在返回给setProperty的函数内部也有一个值。
第二个,U.hoverPopup 调用arrayify 没有this 值,返回的函数中也没有this 值。
我无法理解第二种情况的不同之处。尤其令人困惑的是,this 没有在 setPropertyFunc 的 init 中定义,但 在嵌入函数中定义,而 hoverPopupFunc 的情况正好相反
我真的很希望在这两种情况下都定义this - 在第二种情况下我怎样才能实现呢? (在hoverPopup 的情况下,必须进行一些初始化,所以它并不像“对数组中的每个项目都执行此操作”那么简单)
【问题讨论】:
标签: javascript scope binding this