开发者

JavaScript: firefox refuses the class keyword while chrome doesn't

I was trying this JavaScript piece of code:

class User(name) {
    this.name = name;
}

var class = new User("Kimo");

The above was used as is in a JavaScript book, and I was s开发者_开发技巧imply playing with it.

firefox 6.0.2 (from the console) refused the 'class' keyword as a variable name (complained about a syntax error), while chrome 13.0.782.220m (from the developer tool) didn't complain at all.

It makes me think, which one is right? Since the notion of a class in JavaScript doesn't exist or it is different than other OOP languages. On the other hand, it might be wiser to prevent developers from using it.

I would like to know why this different approaches between firefox and chrome (I know they use different engines).

Thanks


First of all you can`t create a class in Javascript like this. Either create an object:

var User = {...};

or a constructor function:

function User() {...}

class is reserved word from about.com (some not listed in ECMA 262, but present in JScript) and MDC - reserved for future use. It is true that JavaScript has no classes for the moment. But the word is reserved in the sense that some day it can have such.

Mozilla is more strict about the rules than other browsers and gives a syntax error.

In addition :

JavaScript is not purely Object Oriented Programming language ( OOP ) it is Prototype-based Programming language.

On the other hand, it might be wiser to prevent developers from using it.

As JavaScript is interpreted by the browser, I don`t think the usage of reserved words can be prohibited. In the compiled code you have the compiler to disagree with you about such things, before the product is ready to use.

One other thing - you can write JavaScript code on editor with no capabilities to tell you, that your code has errors, or that you use reserved words for variables.


An error is correct behavior. Class is a restricted keyword in ECMAScript.


Firefox didnt implement Class support yet, if you check ecma6 browser support aka javascript(its a new realease that will have more feactures such as class :D), you will see that Class for mozilla isnt possible, lets hope soon will be available, ecma 6 is in beta stage, so it will be a while till all browsers support all the feactures

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜