Angular2-调用Constructor()与new关键字创建对象吗? [英] Angular2 - calling constructor() vs new keyword to create an object?

查看:68
本文介绍了Angular2-调用Constructor()与new关键字创建对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历了Angular2教程,但我真的无法理解类似以下内容之间的区别:

I went through the Angular2 tutorial and i couldn't really understand the difference between something like:

constructor(private _heroService: HeroService) { } 

并创建一个对象,例如

var _heroService: HeroService = new HeroService();

你能澄清吗?

推荐答案

构造函数

constructor(private _heroService: HeroService) { } 

new SomeComponent();

被执行,其中构造函数定义需要将哪些参数传递给new Xxx(...).例如:

is executed, where the constructor defines which parameters need to be passed to new Xxx(...). For example:

new SomeComponent(new HeroService);

如果Angulars DI执行了由Angular创建的新实例new Xxx(...),它将确定从构造函数中自动传递哪些参数.

If a new instance is created by Angular new Xxx(...) is executed by Angulars DI, It figures out which parameters to pass automatically from the constructor.

如果未定义构造函数,则为默认构造函数

If no constructor is defined the default constructor

constructor(){} 

会自动添加到该类中.

is automatically added to the class.

这篇关于Angular2-调用Constructor()与new关键字创建对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆