简体   繁体   English

jQuery返回窗口对象

[英]jQuery returns window object

This is a really stupid question, but for the life of me I can't understand: 这是一个非常愚蠢的问题,但是对于我的一生,我无法理解:

Why $(button).addClass('focus') returns DOMNodes 为什么$(button).addClass('focus')返回DOMNodes

but

(button.addClass || $(button).addClass)('focus') returns the Window object ? (button.addClass || $(button).addClass)('focus')返回Window对象?

EDIT: Is this linked to JavaScript indirect calls, like : (1, alert)('test') ? 编辑:这链接到JavaScript间接调用,如: (1, alert)('test')吗?

jQuery functions can be chained. jQuery函数可以被链接。 This is done by putting return this; 这是通过将return this; at the end of its functions. 在其功能结束时。

However, when you do (button.addClass || $(button).addClass)('focus') , you are dereferencing the function and its context is lost. 但是,当您执行(button.addClass || $(button).addClass)('focus') ,您将取消引用该函数,并且其上下文会丢失。 window is the default context (unless you're in Strict Mode, in which case I think it's null (but as a non-Strict Mode user, I don't know for sure)) which is why you get the Window back. window是默认上下文(除非您处于“严格模式”,在这种情况下,我认为它为null (但我不确定是非严格模式的用户,但我不确定)),这就是为什么您要返回“ Window原因。

Also any attempt to chain this function would fail. 同样,任何链接此功能的尝试都将失败。

What you essentially are doing is this: 您本质上在做的是这样的:

var fn;
if (button.addClass)
    fn = button.addClass;
else
    fn = $(button).addClass;
fn('focus');

Hence, you lose the reference to either button or $(button). 因此,您将丢失对button或$(button)的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM