简体   繁体   English

我如何在angularjs中使用OOP类

[英]How can I use OOP classes in angularjs

I need to know how I can use a class in angularjs. 我需要知道如何在angularjs中使用类。

A simple class like this: 像这样的简单类:

function Person(name,age){
    this.name=name;
    this.age=age;
    this.getAge(){
       return age;
    };
    //etcetera
}

I am learning angular but I can't find an answer to this. 我正在学习有角度的东西,但找不到答案。 I want to create Person instances and use the name, age etc. in the view. 我想创建Person实例,并在视图中使用名称,年龄等。

Please a simple solution because I am from a C# OOP background and don't know js frameworks. 请提供一个简单的解决方案,因为我来自C#OOP背景并且不了解js框架。 But I want to use the MVC pattern. 但是我想使用MVC模式。 Thanks! 谢谢!

AngularJS is a framework that is written in and used through JavaScript. AngularJS是一个用JavaScript编写和使用的框架。 Although JavaScript has many object oriented features, it handles inheritance quite differently. 尽管JavaScript具有许多面向对象的功能,但是它处理继承的方式却大不相同。 This used to be confusing to me too until I read the excellent: JavaScript: The Good Parts by Douglas Crockford. 在我读完优秀的著作《 Douglas Crockford的JavaScript:The Good Parts》之前,这也使我感到困惑。 I suggest you read this, it's quite a brief book and points out differences in approach in a very clear and concise manner. 我建议您阅读此书,这是一本简短的书,并以非常清晰简洁的方式指出了方法上的差异。

Your syntax is almost right, you just need to change the function declaration a bit: 您的语法几乎是正确的,您只需要稍微更改一下函数声明即可:

function Person(name, age) {
    this.name = name;
    this.age = age;

    this.getAge = function () {

        return age;
    };
}

Then you can create an instance like this: 然后,您可以创建一个这样的实例:

var p = new Person("John", 26);

And do a call like this: 并像这样打电话:

console.log(p.name + ' is ' + p.getAge() + ' years old');

Here it is in JS Fiddle . JS Fiddle中

In general, I highly recommend using Typescript , it complements angularjs in an excellent way. 通常,我强烈建议使用Typescript ,它以一种很好的方式补充了angularjs。 It makes your project very scalable, and adds intellisense. 它使您的项目具有很高的可扩展性,并增加了智能感知能力。 You can declare interfaces, classes, etc. 您可以声明接口,类等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM