【LayaBox筆記原創一】LayaBox引入自定義第三方包
阿新 • • 發佈:2019-01-10
【LayaBox筆記一】LayaBox引入自定義第三方包
1、建立Laya專案,選擇ts語言
2、編寫Laya類,例如我們建立一個com.company.Person類
1 /** 2 * 建立一個Person例子 3 * @author wls 4 * @date 2015-01-10 5 */ 6 module com.company { 7 export class Person { 8 public name: string; //公有屬性 9 private id: number; //Person.ts私有屬性 10 private _age: number; //私有屬性,用於getset訪問器 11 private static _sex: string; //靜態屬性, 用於get訪問器 12 13 //帶引數建構函式 14 constructor(id: number) { 15 this.id = id; 16 } 17 18 public get age(): number { 19 return this._age; 20 }21 public set age(value: number) { 22 this._age = value; 23 } 24 25 public static get sex(): string { 26 return this._sex; 27 } 28 29 public static set sex(value: string) { 30 this._sex = value; 31 } 32 33 publicget Id(): number { 34 return this.id; 35 } 36 } 37 }
3、儲存、並編譯,在bin目錄下生成com.company.Person.js 和 com.company.Person.js.map
1 /** 2 * 建立一個Person例子 3 * @author wls 4 * @date 2015-01-10 5 */ 6 var com; 7 (function (com) { 8 var company; 9 (function (company) { 10 var Person = /** @class */ (function () { 11 //帶引數建構函式 12 function Person(id) { 13 this.id = id; 14 } 15 Object.defineProperty(Person.prototype, "age", { 16 get: function () { 17 return this._age; 18 }, 19 set: function (value) { 20 this._age = value; 21 }, 22 enumerable: true, 23 configurable: true 24 }); 25 Object.defineProperty(Person, "sex", { 26 get: function () { 27 return this._sex; 28 }, 29 set: function (value) { 30 this._sex = value; 31 }, 32 enumerable: true, 33 configurable: true 34 }); 35 Object.defineProperty(Person.prototype, "Id", { 36 get: function () { 37 return this.id; 38 }, 39 enumerable: true, 40 configurable: true 41 }); 42 return Person; 43 }()); 44 company.Person = Person; 45 })(company = com.company || (com.company = {})); 46 })(com || (com = {})); 47 //# sourceMappingURL=Person.js.mapPerson.js
4、複製 Person.js 到 bin\libs\ 目錄下,並刪除bin\com.company.Person.js 及其目錄
5、刪除Person.ts檔案及其目錄
6、編寫Person.d.ts提示類
1 /** 2 * 建立一個Person例子 3 * @author wls 4 * @date 2015-01-10 5 */ 6 declare module com.company { 7 export class Person { 8 public name: string; //公有屬性 9 10 //帶引數建構函式 11 constructor(id: number); 12 13 public age: number; 14 15 public static sex:string; 16 //只有get方法的定義 17 public readonly Id:number; 18 19 } 20 }Person.d.ts
7、bin\index.html中,引入Person.js,就可以完成整個自定義第三方庫的實現
1 <!--jsfile--Custom--> 2 <script src="libs/Person.js"></script> 3 <!--jsfile--Custom-->index.html
8、最後我們用個例子來測試一下
1 //呼叫我們定義的第三方類庫 2 var person:com.company.Person = new com.company.Person(123); //例項化一個Person,並傳入ID 3 person.name = "wls"; //設定名稱,直接屬性賦值 4 person.age = 18 //設定年齡,get/set構造器賦值 5 com.company.Person.sex = "安靜的美男子"; //設定性別,靜態get/set構造器賦值 6 //輸出結果 7 console.log(">>>我是一個",com.company.Person.sex,"大名:",person.name,"年年都",person.age);View Code
原始碼和對應操作圖片下載:
連結:https://pan.baidu.com/s/1DpqkTUH1iU9uHdFmDNptjA
提取碼:39nr