简体   繁体   English

ECMAScript类

[英]ECMAScript class

I have the following code which when the web page loads should print the car make and current speed to the console. 我有以下代码,当网页加载时,这些代码应将汽车制造商和当前速度打印到控制台。 Nothing is printed to the console. 什么都没有打印到控制台。 If I put the new object declaration inside a function it does print either. 如果我将新对象声明放入函数中,则不会打印。

<!DOCTYPE html>
<html>
<head>
<script type="application/ecmascript;version=6">

class Car {
    constructor(make) {
    this.make = make;
    this.currentSpeed = 20;
    }

    printCurrentSpeed(){

    console.log(this.make + 'is going ' + this.currentSpeed + 'kmh.');
    }

}

var stang = new Car('Mustang');
stang.printCurrentSpeed();

</script>

    <title>
    </title>
</head>
<body>

</body>
</html>

ES2015 (ex-ES6) classes are not yet natively supported by currently available browsers. 当前可用的浏览器尚不支持ES2015(前ES6)类。 If you want to use them, you will have to use what we call a transpiler : a program which will automatically convert your ES2015 source code into ES5, so that current browsers can run it. 如果要使用它们,则必须使用我们称为transpiler的程序:该程序会自动将ES2015源代码转换为ES5,以便当前的浏览器可以运行它。

The most famous one is currently Babel . 目前最著名的是巴别塔 Another one is Traceur (by Google). 另一个是Traceur (由Google提供)。 Both are good. 两者都很好。

Note that you don't have to use ES2015 to actually have classes. 请注意,您不必使用ES2015实际上课。 ES2015 classes are just a syntaxic sugar around what we call the prototype. ES2015类只是围绕我们所谓的原型的语法糖。 Here is your example without the class keyword: 这是没有class关键字的示例:

function Car(make) {
    this.make = make;
    this.currentSpeed = 20;
}

Car.prototype.printCurrentSpeed = function() {
    console.log(this.make + 'is going ' + this.currentSpeed + 'kmh.');
};

var stang = new Car('Mustang');
stang.printCurrentSpeed();

The class keyword is es6. class关键字是es6。 Currently, it is only available in stable browsers Chrome 42 . 目前,它仅在稳定的浏览器Chrome 42中可用。

Your code can work in Chrome 42 with two modifications: 您的代码可以在Chrome 42中工作,但需要进行以下两项修改:

1) The browser will ignore any script types it does not understand. 1)浏览器将忽略它不理解的任何脚本类型。 Chrome doesn't appear to run any code inside of <script type="application/ecmascript;version=6"></script> . Chrome似乎没有在<script type="application/ecmascript;version=6"></script>内运行任何代码。 You should remove the type. 您应该删除类型。

2) Block scoped declarations ( let , const class ) are only available in strict mode. 2)块作用域声明( letconst class )仅在严格模式下可用。 You need to explicitly opt in: 'use strict'; 您需要明确选择加入: 'use strict';

 <!DOCTYPE html> <html> <head> <script> 'use strict'; class Car { constructor(make) { this.make = make; this.currentSpeed = 20; } printCurrentSpeed(){ console.log(this.make + 'is going ' + this.currentSpeed + 'kmh.'); } } var stang = new Car('Mustang'); stang.printCurrentSpeed(); </script> <title> </title> </head> <body> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM