简体   繁体   中英

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. 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.

The most famous one is currently Babel . Another one is Traceur (by Google). Both are good.

Note that you don't have to use ES2015 to actually have classes. ES2015 classes are just a syntaxic sugar around what we call the prototype. Here is your example without the class keyword:

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. Currently, it is only available in stable browsers Chrome 42 .

Your code can work in Chrome 42 with two modifications:

1) The browser will ignore any script types it does not understand. Chrome doesn't appear to run any code inside of <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. You need to explicitly opt in: '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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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