TypeScript - Prototype 属性


Prototype 属性允许您向对象添加属性和方法。

示例

function employee(id:number,name:string) { 
   this.id = id 
   this.name = name 
} 
var emp = new employee(123,"Smith") 
employee.prototype.email="smith@abc.com" 
console.log("Employee 's Id: "+emp.id) 
console.log("Employee's name: "+emp.name) 
console.log("Employee's Email ID: "+emp.email)

编译时,它将生成以下 JavaScript 代码 −

//Generated by typescript 1.8.10 
function employee(id, name) { 
   this.id = id; 
   this.name = name; 
} 
var emp = new employee(123, "Smith"); 
employee.prototype.email = "smith@abc.com"; 
console.log("Employee 's Id: " + emp.id); 
console.log("Employee's name: " + emp.name); 
console.log("Employee's Email ID: " + emp.email);

其输出如下 −

Employee’s Id: 123 
Emaployee’s name: Smith 
Employee’s Email ID: smith@abc.com

typescript_strings.html