Ember.js 如何定义一个新类
原生JavaScript类是在ES6(或ES2015)中添加的,作为绑定数据和功能的手段。它们允许我们创建一个用户定义的数据类型,其中包含自己独特的数据成员和成员函数,可以通过使用它们的实例(或对象)在代码中访问。
方法: 要在Ember.js中定义一个新类,我们必须使用 class 关键字以及类的名称。然后,我们必须在花括号“{}”内声明类变量和成员函数。我们还可以使用内置的 constructor 函数写入类的默认参数值。之后,我们可以使用“new”关键字创建该类的对象,并在对象定义的参数中初始化构造函数的值,例如 – new Car(carName,carModel,carColor);其中括号内的变量是对象声明的参数。
语法:
// Class declaration
class name_of_class {
constructor(something, random) {
this.something1 = something1;
this.random2= random2;
}
}
我们可以在Ember.js中定义某个类的6种类型的元素:
- 类构造函数
- 成员数据字段(变量)
- 成员函数
- 访问器(Getters和Setters)
- 静态
- 装饰器
示例1:
Javascript
// Defining the class
class Car {
// Initializing a constructor
constructor(name, model, color) {
this.name = name;
this.model = model;
this.color = color;
}
// Defining a member function
print() {
console.log(`Name of Car: {this.name}`);
console.log(`Model of Car:{this.model}`);
console.log(`Color of Car: ${this.color}`);
}
}
// Declaring parameter variables
let carName = "BMW";
let carModel = "E6";
let carColor = "Matte Black";
// Creating an instance of the class
let randomCar = new Car(carName, carModel, carColor);
// Printing the output to the console
randomCar.print();
输出:
示例2:
JavaScript
// Defining the class
class Dog {
// Initializing a constructor
constructor(name, breed) {
this.name = name;
this.breed = breed;
}
// Defining a member function
print() {
console.log(`Name of Dog: {this.name}`);
console.log(`Breed of Dog:{this.breed}`);
}
}
// Declaring parameter variables
let dogName = "Tommy";
let dogBreed = "German Shepherd";
// Creating an instance of the class
let randomDog = new Dog(dogName, dogBreed);
// Printing the output to the console
randomDog.print();
输出: