【LayaBox筆記原創(1)】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; //私有屬性 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 public get 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.map
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 }
7、bin\index.html中,引入Person.js,就可以完成整個自定義第三方庫的實現

1 <!--jsfile--Custom--> 2 <script src="libs/Person.js"></script> 3 <!--jsfile--Custom-->
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);
源碼和對應操作圖片下載:
鏈接:https://pan.baidu.com/s/1DpqkTUH1iU9uHdFmDNptjA
提取碼:39nr
