Is x a reserved keyword in Javascript FF/Safari not in IE?

前端 未结 4 2016
鱼传尺愫
鱼传尺愫 2021-01-24 05:07

A web page of a web application was showing a strange error. I regressively removed all the HTML/CSS/JS code and arrived to the basic and simple code below.

<         


        
相关标签:
4条回答
  • 2021-01-24 05:38

    Still supported by some browsers, before the dom spec, images, a elements and area elements all had read only x and y properties for their coordinates on the page.

    0 讨论(0)
  • 2021-01-24 05:42

    Your problem is with variable scope, not that "x" is reserved. An image object has a property named "x". You can see this with Chrome's developer tools. When you call "alert(x);" on the image object, the "x" in scope is the "x" property on the image.

    0 讨论(0)
  • 2021-01-24 05:51

    I can't seem to find any documentation to support this, but my guess is that the <img> tag is being treated specially, and the object is actually a JavaScript Image object, not a normal DOM element. The Image object has an x property, and so your unscoped reference to x means Image.x. If you want the global x property, just use window.x instead.

    0 讨论(0)
  • 2021-01-24 05:52

    Just to complete the answers from David and Daniel, this behavior is not documented at all, but it work like the following in almost every modern browser:

    The content of an inline event handler becomes the FunctionBody of a function that the browser calls when it fires that event.

    The scope chain of this function is augmeted with the element, the element's FORM (if it exits and is a FORM element), and document itself.

    It looks something like this in code:

    function onclick(event) {
      with(document) {
        with(this.form) {
          with(this) {
            // inline event handler content...
          }
        }
      }
    }
    

    This behavior can cause all sort of name conflicts due the augmentation of the scope chain you cannot be 100% sure about what you are referring, it could be an attribute of the element itself, an attribute of the element's form, an attribute of the document object or any global variable.

    Recommended article:

    • Unsafe Names for HTML Form Controls
    0 讨论(0)
提交回复
热议问题