如何在 Ember.js 中定义一个新类?
ES6(或 ES2015)中添加了 JavaScript 中的原生类,作为将数据和函数绑定在一起的手段。它们允许我们创建一个用户定义的数据类型,该类型由其自己的唯一数据成员和成员函数组成,可以通过使用它们的实例(或对象)在代码中访问它们。
方法:要在 Ember.js 中定义一个新类,我们必须使用class关键字和类名。然后我们必须在花括号“{}”中声明类变量和成员函数。我们还可以使用内置的构造函数来编写类的默认参数值。之后,我们可以通过使用“new”关键字并在对象定义的参数中初始化构造函数值来创建该类的对象,例如 - new Car(carName, carModel, carColor);其中括号内的变量是对象声明的参数。
句法:
// Class declaration
class name_of_class {
constructor(something, random) {
this.something1 = something1;
this.random2= random2;
}
}
我们可以在 Ember.js 中的某个类中定义 6 种类型的元素:
- 类构造函数
- 成员数据字段(变量)
- 成员函数
- 访问器(Getter 和 Setter)
- 静止的
- 装饰器
示例 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();
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();
输出:
示例 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();
输出: