var l = {
install: function(v, s, G) {
window[v] = function(m) {
console.log(m, this.s, this.G);
}
window[v].v = v;
window[v].s = s;
window[v].G = G;
return;
}
};
l.install('xx5', '11', {
a: 4
});
xx5('i hope this works');
//undefined
window.xx5('?');
//undefined
我想知道为什么没有错误或日志
我不想知道可选的解决方案,我之所以感到困惑,仅仅是因为xx5()函数似乎启动了,但没有日志记录,而且没有错误
这怎么会导致绝对沉默呢?
我期待看到:
'i hope this works' 11 {a:4}
'?' 11 {a:4}
发布于 2021-07-20 12:19:48
无论您附加了什么属性,s
、v
、G
都附加在window['xx5']
上。
在运行您的函数时:
xx5('i hope this works'); // No object, so `this` belongs to the window object
window.xx5('?'); //Attached to the window object, so once again `this` belongs to the window object
当您寻找this.s
时,您是在寻找window.s
。这显然是undefined
。
您可以这样做以获得预期的输出:
var l = {
install: function(v, s, G) {
window[v] = function(m) {
console.log(m, this[v].s, this[v].G);
}
window[v].v = v;
window[v].s = s;
window[v].G = G;
return;
}
};
l.install('xx5', '11', {
a: 4
});
xx5('i hope this works');
//undefined
window.xx5('?');
//undefined
https://stackoverflow.com/questions/68460711
复制相似问题