TypeScript入门笔记
1.Interface and Implementation
interface IThing{ name:string; age:number; sayHello:{ (name:string):string; (age:number):number; //override this function, sayHello() has two signatures.
new (name:string):Element; //placeholder for further investigation
[index:number]:Date; //index; } } class Thing implements IThing{ name:string;
age:number;
constructor(public name:string, public age:number){//...}
//sayHello() implementation:先声明要实现的重载函数,再实现;如下:
//1.override signature #1
sayHello(name:string):string;
//2.override signature #2
sayHello(age:number):number
//implementation:
sayHello(arg:any):any{
if(typeof arg === 'string'){
return 'hello, ' + arg;
}else if(typeof arg === 'number'){
return arg*2;
}else
{
throw new Error('invalid input args!!!');
}
}
}
1.1 constructor
.ts
interface ICar{engine:string;}
class Car{ //或者写成:class Car implements ICar,下边代码不用做改变,因为已经有了public了,也不用在Car里边声明engine了。
constructor(public engine:string){
}
}
.js
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
return Car;
})();
2.objects
// person: {name: string, age: number, getPets: () => string[] }
var person ={
name:'Colleen', //name is known as a string;
age:25, //age is known as a number;
getPets:function(){
return['Spot','Nemo','Pascal']; //返回字符串数组;
}
}
3.Arrow Function(familiar with lembda expressions)
var myFunc1 =function(h: number, w: number){ return h * w;};
var myFunc2 =(h: number, w: number)=> h * w;
4.Value Proposition (x: string[]) => number)
function getArrayLength(x: string[]) {
var len = x[0].length;
return len;
}
var names = ['John', 'Dan', 'Aaron', 'Fritz'];
Console.log(getArrayLength(names)) //names is a string array, works fine;
var people = [{name: 'Aaron'}, {name: 'Fritz'}];
Console.log(getArrayLength(people)) //get errors as people's type is not compatible;
5.Class(fields,properties,.ctor,functions[static, prototype, instance based])
类,最起码:1)可以创建多个实例; 2)可以继承; 3)单例。
基本语法:
class Car{
engine:string; //属性,默认为public,设为private可以防止外部访问;
constructor(engine:string){ this.engine = engine;} //.ctor
}
Class Car会生成对应的javascript代码:
var Car = (function(){
function Car(engine){this.engine = engine;}
return Car
}
)();
6.打个岔
public class Bar
{
public Bar(Foo foo)
{
}
}
public class Foo
{
private Bar _bar =new Bar(this); //error occurs, cannot use 'this' in variable initializer;实例的某个变量初始化不能引用本实例,原因是Member //initializers run before class constructor。
//http://stackoverflow.com/questions/6125247/why-cant-you-use-this-in-member-initializers
}
——————————————————————————————workaround———————————————————————————————
public class Foo
{
private Bar _bar;
public Foo()
{
_bar =new Bar(this); //字段的初始化是在实例初始化之前进行,所以不能在字段中引用本实例this(此时this还不存在),但在实例的.ctor中是可以的。
}
}
7.Function
插入语:javascript中可以定义匿名函数:
isBetween= new Function("a","b","c","if((a>=b)&&(a<=c))return(true);else return(false);"); //Function跟String,Boolean一样,可以new;
相当于:function isBetween(a, b, c){ //if...else...;}
prototype(主要用于添加public method,要创建多个对象的话,用此方法可以节省空间,Because the prototype can save you some memory as it only exists once while creating a function on every instance of the class would create 1 function per instance.):
.ts
class Car{
start(){//...}
}
生成对应的js是:
var Car = (function(){
Car.prototype.start = function(){ //...}
})();
instance member
.ts
class Car{
stop:()=>string;
constructor(){this.stop=()=>"blah blah blah...";}
}
8.Inheritance
8.1.class inheritance 原文链接http://www.johnpapa.net/typescriptpost3/
.ts
class Auto{ engine:string; constructor(engine:string){ this.engine = engine; } } class Truck extends Auto{ bigTires:bool; constructor(engine:string,bigTires:bool){ super(engine); this.bigTires = bigTires;
} }
对应的javascript
var __extends = this.__extends || function (d, b) { //__extends variable is used to do class extends. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Auto = (function () { function Auto(engine) { this.engine = engine; } return Auto; })(); var Truck = (function (_super) { __extends(Truck, _super); function Truck(engine, bigTires) { _super.call(this, engine); this.bigTires = bigTires; } return Truck; })(Auto);
8.2.Interface
ts中的接口可以用来定义复杂类型
// TypeScript interface ICar{ engine: string; color: string; } class Car implements ICar { constructor (public engine: string, public color: string) { //构造函数的简单写法,即不用定义engine和color,传入参数时会自动定义为public;
} }
除了实现,还可以用接口定义变量(这跟其他OOP语言一样),如ts: var toyotaCamry: ICar;
9.Modules(internal and external)
为了方便起见,john又把internal module分成implicit module和named module(Typescript Spec.中找不到,只是他自己的想法);比如想用AMD或者CommonJS的话,可能会选择external modules;相反,如果想将代码组织成命名文件,named modules是比较好的选择。
1.implicit internal modules(无名module)
typescript code file:
class TestClass{
private a = 2;
public b = 4;
}
var t = new TestClass();
上边直接写代码块,不用担心module问题;一个ts文件的全部内容就是一个module,没名字,所有东西都在global scope中;this is not a good practice!
2.named internal modules(命名module,关键词module)
module Shapes { class Rectangle { constructor ( public height: number, public width: number) { } } // This works! var rect1 = new Rectangle(10, 4); } // This won't!! var rect2 = Shapes._________
使用module关键字,所有代码的范围就是这个module scope,而且会从global scope中移除;这个module本身是在global scope中的,module可以嵌套;如下:
module Shapes{ class Rectangle{ constructor(public height:number, public width:number){} } //this works! var rect1 = new Rectangle(23,34); } //this won't!! var rect2 = Shapes.___
3.exports
module Shapes{ export class Person{ constructor( public name:string, public age:number ){} } } var p = new Shapes.Person("paul cheung", 21) //export关键字标识可以从外部访问;this works fine!!
对应的js为:
var Shapes; (function (Shapes) { var Person = (function () { function Person(name, age) { this.name = name; this.age = age; } return Person; })(); Shapes.Person = Person; })(Shapes || (Shapes = {})); var p = new Shapes.Person("paul cheung", 21);
还可以对internal modules进行扩展,在多个文件中共享,使用:///<reference path="shapes.ts" />
4.External modules
PS:js文件非常多的应用中,要处理js加载管理问题,使用RequireJS!要求apps的scale时,应当考虑AMD(Asynchronous Module Definition,refers to http://blog.csdn.net/songchunyi/article/details/7918483);TypeScript支持AMD(使用external module);建议使用RequireJS实现AMD。
当使用AMD(或CommonJS)和external modules的时候,可以export整个module,然后import到另一个module中,这便形成了依赖链(dependency chain),这种依赖关系可以通过AMD,require.js来管理
posted on 2013-07-31 19:49 paul_cheung 阅读(613) 评论(0) 编辑 收藏 举报