Browser support for using a reserved word as a property name in JavaScript

后端 未结 4 1026
一个人的身影
一个人的身影 2020-11-30 09:06

I\'m trying to use \"for\" as an object property name. It seems to work fine in IE7, IE8, Firefox, Chrome and Opera, but apparently not in Safari.

My understanding

相关标签:
4条回答
  • 2020-11-30 09:27

    after study, I think I can prove that using reserved words as property names (if done with a little common sense) is harmless, whether in the obj['name'] or obj.name syntax.

    see this stackoverflow question

    0 讨论(0)
  • 2020-11-30 09:37

    You can use those words, but only as strings and not shorthand properties.

    foo['class']; // cool
    foo.class;    // not cool
    

    But here is the actual list you requested. None of these can be used via property dot syntax. https://web.archive.org/web/20140902235313/http://javascript.about.com/library/blreserved.htm


    Also, only slightly tangential, CoffeeScript notices this and auto stringifies them for you. http://jashkenas.github.com/coffee-script/#literals

    Input:

    $('.account').attr class: 'active'
    log object.class
    

    JS Ouptput:

    $('.account').attr({
      "class": 'active'
    });
    log(object["class"]);
    

    I happen to think that is pretty dang neat.

    0 讨论(0)
  • 2020-11-30 09:44

    Perhaps the question is not so much whether reserved words can be used as property names for objects - they can. Seems like the real question here is whether they can be used naked (ie. without being clothed in quotes). Naked use of reserved words is supported from ES5 onwards, but not all interpreters support ES5 features yet. As mentioned, there is a good table here...

    http://kangax.github.io/es5-compat-table/#Reserved%20words%20as%20property%20names

    If you're just doing some coding in NodeJS, then you don't have to worry about this type of issue. If you care about portability of your code to a wide variety of environments (without using a language like CoffeeScript that compiles to JavaScript), then your code should quote the reserved words...

    defining...

    var foo = {'for':'this works'};
    

    accessing...

    foo ['for'];
    
    0 讨论(0)
  • 2020-11-30 09:45

    There is a table showing browser support for ECMAScript 5 features here: http://kangax.github.com/es5-compat-table/

    Reserved words can be used as property names in IE9, Firefox 3.5+ and Chrome 7+, Safari 5.1+.

    0 讨论(0)
提交回复
热议问题