class
语法只是一种语法,而不是面向对象范例的完整的基于类的实现,不像Java,Python或Ruby等语言。在ES5中,我们通常定义一个构造函数function,并使用new
关键字实例化一个对象。 var SpaceShuttle = function(targetPlanet){类语法只是替换构造函数创建:
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
class SpaceShuttle {请注意,
构造(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
class
关键字声明了一个新函数,并添加了一个构造函数,该函数将在调用new
调用 - 以创建新对象。 class
关键字并编写适当的构造函数来创建Vegetable
类。使用Vegetable
可以创建具有属性name
的蔬菜对象,以传递给构造函数。 Vegetable
应该是一个class
具有限定constructor
方法。
testString: 'assert(typeof Vegetable === "function" && typeof Vegetable.constructor === "function", "Vegetable
should be a class
with a defined constructor
method.");'
- text: class
关键字。
testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"class
keyword was used.");'
- text: Vegetable
可以实例化。
testString: 'assert(() => {const a = new Vegetable("apple"); return typeof a === "object";},"Vegetable
can be instantiated.");'
- text: carrot.name
应该返回carrot
。
testString: 'assert(carrot.name=="carrot","carrot.name
should return carrot
.");'
```