函数

函数类型

1
2
3
4
5
6
7
8
function add(x: number, y: number): number {
return x + y;
}

let myAdd = function(x: number, y: number): number { return x + y; };

let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x + y; };

推断类型

1
2
3
4
5
6
// myAdd has the full function type
let myAdd = function(x: number, y: number): number { return x + y; };

// The parameters `x` and `y` have the type number
let myAdd: (baseValue: number, increment: number) => number =
function(x, y) { return x + y; };

可选参数和默认参数

1
2
3
4
5
6
7
8
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}

let result1 = buildName("Bob"); // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined); // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result4 = buildName("Bob", "Adams"); // ah, just right

剩余参数

1
2
3
4
5
6
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

this

JavaScript里,this的值在函数被调用的时候才会指定。

this和箭头函数

重载

1

传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从ECMAScript 2015,也就是ECMAScript 6开始,JavaScript程序员将能够使用基于类的面向对象的方式。

阅读全文 »

接口

TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

阅读全文 »

变量声明

var

let

拥有块级作用域的变量的另一个特点是,它们不能在被声明之前读或写。 虽然这些变量始终“存在”于它们的作用域里,但在直到声明它的代码之前的区域都属于 暂时性死区。 它只是用来说明我们不能在 let语句之前访问它们。

阅读全文 »

Mongoose

Mongoose 是在 node 环境下对 MongoDB 进行便捷操作的对象模型工具。

阅读全文 »

sublime 配置4个空格代替Tab

1
2
3
4
5
6
{
// The number of spaces a tab is considered equal to
"tab_size": 4,
// Set to true to insert spaces when tab is pressed
"translate_tabs_to_spaces": true
}
阅读全文 »

Jasmine 是一个用 Javascript 代码的行为驱动测试框架,它不依赖于任何其它 Javascript 框架。Jasmine 与 Mocha 大概是目前最火的两个单元测试框架了。

阅读全文 »

关于函数防抖和函数节流,相信你已经听过了很多遍了。但是两者的差别,你能快速准确的说出来吗?下面,我们就来聊一聊函数防抖和函数节流的本质区别和实现。

阅读全文 »

一般情况下,在移动开发过程中,针对click事件,浏览器会有300ms的派发延迟。由于这300ms的延迟,通常会带来一些问题,比如点击穿透。那么浏览器为什么有300ms的延迟呢?

阅读全文 »