是否有方法在AngularJS中创建/模拟“类”来预定义属性、构造函数和方法。我想创建一个普通的JavaScript“类”文件,但是如何将它包含在AngularJS项目中呢?
var Pastry = {
// initialize the pastry
init: function (type, flavor, levels, price, occasion) {
this.type = type;
this.flavor = flavor;
this.levels = levels;
this.price = price;
this.occasion = occasion;
},
// Describe the pastry
describe: function () {
var description = "The " + this.type + " is a " + this.occasion + " pastry, has a " + this.flavor + " flavor, " + this.levels + " layer(s), and costs " + this.price + ".";
return description;
}
};或
function Pastry(type, flavor, levels, price, occasion) {
this.type = type;
this.flavor = flavor;
this.levels = levels;
this.price = price;
this.occasion = occasion;
}
Pastry.prototype.describe = function () {
var description = "The " + this.type + " is a " + this.occasion + "pastry, has a " + this.flavor + " flavor, " + this.levels + " layer(s), and costs " + this.price + ".";
return description;
}发布于 2020-01-14 11:10:22
我将选择JavaScript对象使用原型继承的第二个示例。因此,使用它会给出最类似类的代码。然而,class关键字并不是AngularJS独有的,它是一种用原型继承的方法、getter和setter编写构造函数的不同方法。
使用import和export (JS模块指南)在其他文件中使用class或任何其他值。用export定义可以导出哪些变量、函数或类。在另一个文件中,使用文件顶部的import将导出的值导入到自己的文件中。
所以把所有的都放在一起。
您仍然可以选择使用function关键字并手动编写prototype对象。
function Pastry(type, flavor, levels, price, occasion) {
...
}
Pastry.prototype.describe = function () {
...
}
export default Pastry;或者用class关键字来完成它。最终的结果将几乎完全一样。
export default class Pastry {
constructor(type, flavor, levels, price, occasion) {
...
}
describe() {
...
}
}注意default关键字。它将指示,只要我们不指定要导入的值,就应该导入默认值。
import Pastry from './pastry.js';from关键字从相对于其所在文件的路径检索值。因此,在本例中,上面的pastry.js文件位于同一个目录中,是带有import语句的文件。
https://stackoverflow.com/questions/59731883
复制相似问题