1. constructor
constructor應該是ES6中明確使用constructor來表示構造函數(shù)的,構造函數(shù)使用在class中,用來做初始化操作。當包含constructor的類被實例化時,構造函數(shù)將被調(diào)用。
來看例子:
class AppComponent { public name: string; constructor(name) { console.log('Constructor initialization'); this.name = name; }}let appCmp = new AppComponent('AppCmp'); // 這時候構造函數(shù)將被調(diào)用。console.log(appCmp.name);轉(zhuǎn)成ES5代碼如下:
var AppComponent = (function () { function AppComponent(name) { console.log('Constructor initialization'); this.name = name; } return AppComponent; // 這里直接返回一個實例}());var appCmp = new AppComponent('AppCmp');console.log(appCmp.name);2. ngOnInit
ngOnInit是Angular中OnInit鉤子的實現(xiàn)。用來初始化組件。
Angular中生命周期鉤子的調(diào)用順序如下:
在Angular銷毀指令/組件之前調(diào)用。
了解了這些之后我們來看一個例子:
import { Component, OnInit } from '@angular/core';@Component({ selector: 'my-app', template: ` <h1>Welcome to Angular World</h1> `,})export class AppComponent implements OnInit { constructor() { console.log('Constructor initialization'); } ngOnInit() { console.log('ngOnInit hook has been called'); }}這里輸出的是:
Constructor initialization
ngOnInit hook has been called
可以看出,constructor的執(zhí)行是在先的。
那么既然ngOnchanges是輸入屬性值變化的時候調(diào)用,并且ngOnInit是在ngOnchanges執(zhí)行完之后才調(diào)用,而constructor是在組件就實例化的時候就已經(jīng)調(diào)用了,這也就是說,在constructor中我們是取不到輸入屬性的值的。
所以還是看例子:
// parent.component.tsimport { Component } from '@angular/core';@Component({ selector: 'exe-parent', template: ` <h1>Welcome to Angular World</h1> <p>Hello {{name}}</p> <exe-child [pname]="name"></exe-child> <!-- 綁定到子組件的屬性 --> `,})export class ParentComponent { name: string; constructor() { this.name = 'God eyes'; }}
|
新聞熱點
疑難解答
圖片精選