import { Component } from '@angular/core';
import { Router } from '@angular/router';
import {SampleComponent} from './sample.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor( public router: Router){
}
nextPage(){
this.router.navigate(['/nextpage']);
}
}
//第2行输出:5 //编译器输出读取函数a()
//第6行输出:未定义//执行结果x()
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import {SampleComponent} from './sample.component';
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{
path: " ",
component: AppComponent
},
{
path: "nextpage",
component: SampleComponent
}
];
@NgModule({
imports: [ BrowserModule, FormsModule,RouterModule.forRoot(appRoutes) ],
declarations: [ AppComponent, HelloComponent,SampleComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
输出:“约翰”
function a() {
console.log(5);
return;
}
var x = a;
x();
//第5行输出:“ pedro”
//第9行输出:undefined //执行结果x()
有人向我解释发生了什么吗?因为输出不是: 'john'->此处显示为'pedro',person.first语句首先执行console.log(this.first) 'pedro'->这里给出未定义,与上面的情况相同
答案 0 :(得分:1)
您的问题用词奇怪,但我会尽力回答。
var person = {
first: 'John',
last: 'Smith',
full: function() {
console.log(this.first);
}
};
当定义一个函数而没有返回值时,未定义的总是返回给调用者。 JavaScript函数总是返回某些内容。
如果要使用该函数中的变量,则必须声明一个返回值。
您可以通过命名空间来获取对象的变量,在您的示例中,您可以这样做:person.first
,person.last
。
如果您希望函数返回某些内容,则可以这样声明person:
var person = {
first: 'John',
last: 'Smith',
full: function() {
return this.first + " " + this.last;
}
};