我有以下的代码,当网页加载时,应该打印汽车制造和当前的速度到控制台。控制台上没有打印任何内容。如果我将新的对象声明放入函数中,它也会打印。
<!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>发布于 2015-06-15 14:32:16
class关键字是es6。目前,它只能在稳定的浏览器铬42中使用。
您的代码可以在Chrome 42中工作,只需进行两次修改:
1)浏览器将忽略它不理解的任何脚本类型。Chrome似乎没有在<script type="application/ecmascript;version=6"></script>内部运行任何代码。你应该删除类型。
2)块作用域声明(let、const class)只能在严格模式下使用。您需要显式地选择:'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>
发布于 2015-06-15 14:27:34
ES2015 (ex-ES6)类还没有得到当前可用浏览器的本地支持。如果您想要使用它们,您必须使用我们所称的转换程序:一个自动将ES2015源代码转换为ES5的程序,以便当前的浏览器能够运行它。
目前最著名的是巴贝尔。另一个是谷歌( 示踪剂 )。两者都很好。
请注意,您不必使用ES2015来实际拥有类。ES2015类只是我们所称的原型周围的一个语法糖。下面是没有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();https://stackoverflow.com/questions/30847617
复制相似问题