leesider
leesider

Reputation: 109

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>

Upvotes: 0

Views: 130

Answers (2)

Ma&#235;l Nison
Ma&#235;l Nison

Reputation: 7353

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();

Upvotes: 2

Nathanael Smith
Nathanael Smith

Reputation: 3311

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>

Upvotes: 1

Related Questions