开发者

Is name a special attribute when dealing with JavaScript function

<body>
<script type="text/javascript">
    function name(firstname)
    {
        alert("Your firstname: " + firstname);  
    }
</script>

<form>
 开发者_开发知识库   <input type="button" value="Do it" onclick="name('aaron')"/>
</form>
</body>

This will not work in Chrome/IE8. IE8 states Object doesn't support this action. It has to do with the name of the function being name. If I change the name of the function to people it works...what gives?


It's not a reserved word, and it's not a clash with window.name. There are problems with using a window property name as a global variable in IE, but it's OK as long as you have declared them globals using the var or function keywords as you have here.

What you have here is a strange—and, as far as I can see, undocumented—IE quirk (copied by WebKit) where, in event handlers declared via inline attribute, the properties of the target element are treated as local variables. This is presumably so you can write code like:

<input name="foo" value="bar" onclick="alert(name+': '+value)"/>  // foo: bar

'cos saying this.name is too hard, apparently. Once again IE trying to be “convenient” causes weird unpredictable bugs.

This is just another reason not to use inline event handler attributes. Without them:

<input id="doit" type="button" value="Do it"/>

<script type="text/javascript">
    document.getElementById('doit').onclick= function() {
        name('bob');
    };
</script>

works fine.


Expanding on the previous answers (sorry, I can't comment yet!), name is not exactly a reserved word.

https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/name

Chrome misinterprets this line as trying to access the anonymous function (created by your inline event handler)

<input type="button" value="Do it" onclick="name('aaron');"/>

You can get the intended behavior by doing

<input type="button" value="Do it" onclick="window.name('aaron');"/>


"name" is an attribute of the window (global) object defined in HTML5. It is NOT a reserved JavaScript word (you can find a list of reserved keywords here), but since it's defined in HTML5, using "name" as a function/variable name is not advisable for JavaScript code developed for use with HTML pages.


It's because the window object (which is the global scope) already has a property named name.

The name name is not a reserved keyword, and works fine in other scopes (e.g. a local variable). You should avoid to use it though, as you might inadvertently use the property in the windowobject instead of the variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜