JavaScript中的this和self之间的区别 [英] Difference between this and self in JavaScript

查看:195
本文介绍了JavaScript中的this和self之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都知道javascript中的这个,但是在野外遇到了 self 的实例,例如如此处

Everyone is aware of this in javascript, but there are also instances of self encountered in the wild, such as here

那么,JavaScript中这个 self 之间有什么区别?

So, what is the difference between this and self in JavaScript?

推荐答案

除非在别处设置,否则 self 的值为窗口因为 JavaScript 允许您访问任何属性 x 窗口简单地 x ,而不是 window.x 。因此, self 实际上是 window.self ,与 this

Unless set elsewhere, the value of self is window because JavaScript lets you access any property x of window as simply x, instead of window.x. Therefore, self is really window.self, which is different to this.

window.self === window; // true

如果您正在使用在全局范围内执行且不在严格模式,默认为窗口,因此

If you're using a function that is executed in the global scope and is not in strict mode, this defaults to window, and therefore

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

如果您在不同的上下文中使用某个函数,这个将引用该上下文,但 self 仍然是 window

If you're using a function in a different context, this will refer to that context, but self will still be window.

// invoke foo with context {}
foo.call({}); // true false false

你可以找到 window.self Window Object / em> 此处

You can find window.self defined in the W3C 2006 working draft for the Window Object here.

这篇关于JavaScript中的this和self之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆