首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS中的对象建模

AngularJS中的对象建模
EN

Stack Overflow用户
提问于 2020-01-14 10:27:13
回答 1查看 36关注 0票数 0

是否有方法在AngularJS中创建/模拟“类”来预定义属性、构造函数和方法。我想创建一个普通的JavaScript“类”文件,但是如何将它包含在AngularJS项目中呢?

代码语言:javascript
复制
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;
  }
};

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-14 11:10:22

我将选择JavaScript对象使用原型继承的第二个示例。因此,使用它会给出最类似类的代码。然而,class关键字并不是AngularJS独有的,它是一种用原型继承的方法、getter和setter编写构造函数的不同方法。

使用importexport (JS模块指南)在其他文件中使用class或任何其他值。用export定义可以导出哪些变量、函数或类。在另一个文件中,使用文件顶部的import将导出的值导入到自己的文件中。

所以把所有的都放在一起。

您仍然可以选择使用function关键字并手动编写prototype对象。

代码语言:javascript
复制
function Pastry(type, flavor, levels, price, occasion) {
  ...
}

Pastry.prototype.describe = function () {
  ...
}

export default Pastry;

或者用class关键字来完成它。最终的结果将几乎完全一样。

代码语言:javascript
复制
export default class Pastry {

  constructor(type, flavor, levels, price, occasion) {
    ...
  }

  describe() {
    ...
  }

}

注意default关键字。它将指示,只要我们不指定要导入的值,就应该导入默认值。

代码语言:javascript
复制
import Pastry from './pastry.js';

from关键字从相对于其所在文件的路径检索值。因此,在本例中,上面的pastry.js文件位于同一个目录中,是带有import语句的文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59731883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档