每个人都知道 javascript 中的 this
,但也有在野外遇到的 self
实例,例如 here
那么,JavaScript 中的this
和self
有什么区别呢?
最佳答案
除非在其他地方设置,否则 self
的值是 window
因为 JavaScript 允许您访问任何属性 x
window
为 x
,而不是 window.x
。因此,self
实际上是 window.self
,这不同于 this
.
window.self === window; // true
如果你正在使用一个在全局范围内执行的函数并且不是在严格模式下,this
默认为 window
,因此
function foo() {
console.log(
window.self === window, // is self window?
window.self === this, // is self this?
this === window // is this window?
);
}
foo(); // true true true
如果您在不同的上下文中使用函数,this
将引用该上下文,但 self
仍将是 window
。
// invoke foo with context {}
foo.call({}); // true false false
您可以在 W3C 2006 working draft for the Window Object here 中找到定义的 window.self
.
关于javascript - JavaScript 中 this 和 self 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875767/