Q
差异
47
A
回答
55
除有其他地方的self
值window
因为的JavaScript可以访问,而不是window.x
任何财产window
简单地x
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 Objecthere定义window.self
。
+9
为了完整起见,当窗口不可访问时,“self”在WebWorker环境中非常有用(https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/ Using_web_workers)。使用''self''而不是''window''可以让你以便携的方式访问全局对象。 – lqc
16
虽然我迟到了这里,但我碰到一个例子也可以帮助才明白this
进一步:
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
O/P
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
此前ECMA 5 ,内函数中的
this
会引用全局窗口对象;而在ECMA 5中,内部函数中的this
将是未定义的。
相关问题
[并关于此](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)... –
@dystroy:有一个:[' window.self'](https://developer.mozilla.org/en-US/docs/Web/API/window.self)('=== window')。尽管OP可能意味着一个简单的变量名... – Bergi
哦,这个你认为呢?那么......也许你应该回答。 –