首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ECMAScript类

ECMAScript类
EN

Stack Overflow用户
提问于 2015-06-15 14:21:44
回答 2查看 120关注 0票数 0

我有以下的代码,当网页加载时,应该打印汽车制造和当前的速度到控制台。控制台上没有打印任何内容。如果我将新的对象声明放入函数中,它也会打印。

代码语言:javascript
复制
<!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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-15 14:32:16

class关键字是es6。目前,它只能在稳定的浏览器铬42中使用。

您的代码可以在Chrome 42中工作,只需进行两次修改:

1)浏览器将忽略它不理解的任何脚本类型。Chrome似乎没有在<script type="application/ecmascript;version=6"></script>内部运行任何代码。你应该删除类型。

2)块作用域声明(letconst class)只能在严格模式下使用。您需要显式地选择:'use strict';

代码语言:javascript
复制
<!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>

票数 1
EN

Stack Overflow用户

发布于 2015-06-15 14:27:34

ES2015 (ex-ES6)类还没有得到当前可用浏览器的本地支持。如果您想要使用它们,您必须使用我们所称的转换程序:一个自动将ES2015源代码转换为ES5的程序,以便当前的浏览器能够运行它。

目前最著名的是巴贝尔。另一个是谷歌( 示踪剂 )。两者都很好。

请注意,您不必使用ES2015来实际拥有类。ES2015类只是我们所称的原型周围的一个语法糖。下面是没有class关键字的示例:

代码语言:javascript
复制
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();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30847617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档