一、函数的声明和使用
函数是一组一起执行多条语句的组合,形成可重用的代码块。 通过function关键字声明要告诉编译器函数的名称、返回类型和参数以及执行的内容。
function printStudentsInfo(students: string[]): void
for (let student of students) {
console.log(student);
}
}
printStudentInfo([ '嘻嘻', '哈哈', '努力 '奋斗']);
console.log('-----------------------------------');
printStudentInfo([ '嘻嘻', '哈哈', '努力 '奋斗']);
二、函数的声明和使用
箭头函数/lambda表达式 简化函数声明,通常用于需要一个简单函数的地方
- 箭头函数的返回类型可以省略,省略时,返回类型通过函数体推断
const printinfo = (name: string): void => {
console.log(name)
};
- 执行体只有一行的情况下可以省略花括号
const printinfo = (name: string) => console.log(name);
printlnfo('90后晨仔');
- 箭头函数常用于作为回调函数
let students: string[] = ['北京', '天津', '太原', '石家庄'];
students.forEach((student: string) => console.log(student));
三、闭包的声明和使用
闭包函数一个函数可以将另一个函数当做返回值,保留对内部作用域的访问。
function outerFunc(): () => string {
let count = 0
return (): string => {
count++;
return count.toString()
}
}
let invoker = outerFunc()
console. log(invoker()) // 输出:1
console. log(invoker()) // 输出:2
四、函数作为返回值类型
将一个函数声明定义为一个类型,函数参数或者返回值。
五、类的声明与创建
- 类的声明
ArkTS支持基于类的面向对象的编程方式,定义类的关键字为class,后面紧跟类名。 类的声明描述了所创建的对象共同的属性和方法。
class Person {
name: string = '90后晨仔';
age: number = 30;
isMale: boolean = true;
}
- 类的创建
const person = new Person();
console.log(person.name); // 输出:90后晨仔
const person: Person = ( name: '90后晨仔', age: 29, isMale: true };
console.log(person.name); // 输出:90后晨仔
六、构造器
constructor用于实例化时进行初始化操作。
class Person {
name: string = '90后晨仔';
age: number = 29;
isMale: boolean = true;
constructor(name: string, age: number, isMale: boolean){
this.name = name;
this.age = age;
this.isMale = isMale;
}
}
const person = new Person('90后晨仔'32, false);//在这里通过传入参数实例化
console.log (person.name); // 输出:90后晨仔
七、方法
用于描述定义类的实例对象具有的行为。
八、封装
把数据隐藏起来,只对外部提供必要的接口来访问和操作数据,确保数据的一致性和安全性。
九、继承
子类继承父类的特征和行为,使得子类具有父类相同的行为。ArkTS中允许使用继承来扩展现有的类,对应的关键字为extends。
十、多态
子类继承父类,并且可以重写父类方法,使不同的实例对象对同一行为有不同的表现。