为什么我不能直接将document.getElementById分配给不同的函数?

编程入门 行业动态 更新时间:2024-10-21 15:54:58
本文介绍了为什么我不能直接将document.getElementById分配给不同的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我试图定义一个类似于document.getElementById的函数g()。以下工作正常:

So I'm trying to define a function g() that is like document.getElementById. The following works just fine:

var g = function(id){return document.getElementById(id)};

但为什么这个更直接的代码不起作用?

But why doesn't this more direct code work?

var g = document.getElementById;

推荐答案

问题在于 context 。当您触发对象的函数时,它将使用该对象作为 this 的值触发(除非您另行指定)。 g = document.getElementById 将函数 getElementById 放入变量 g ,但没有设置上下文。

The problem is that of context. When you fire an object's function, it is fired with the object as the value of this (unless you specify otherwise). g = document.getElementById puts the function getElementById into the variable g, but doesn't set the context.

因此,当你运行 g(someId)时,那里没有函数可以运行的上下文。它使用全局对象窗口作为此的值运行,但这不起作用。 (确切地说,它不起作用,因为你可以使用任何文档对象,而不仅仅是 window.document ,你还没有指定一个。)

Therefore, when you run g(someId), there is no context on which the function can run. It is run with the global object window as the value of this, and that doesn't work. (To be precise, it doesn't work because you could be operating with any document object, not just window.document, and you haven't specified one.)

可以通过调用,你设置上下文:

You could get around this with call, where you set the context:

g.call(document, someId);

但是,这不是原来的改进!

However, this isn't an improvement over the original!

更多推荐

为什么我不能直接将document.getElementById分配给不同的函数?

本文发布于:2023-07-29 08:55:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   document   getElementById

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!