2017-05-04 45 views
3

現在我想實現一個數組代理。這裏是我的代碼如何擴展和重寫打印機中的數組方法

class ArrayProxy<T> extends Array<T> { 

    constructor(data: T[]) { 
     super(...data); 
    } 

    push(...items: T[]): number { 
     var res = super.push(...items); 
     console.log("push invoked!"); 
     // some code to do extra operation. 
     return res; 
    } 
} 

var foo = new ArrayProxy(["aa","bb"]); 
foo.push("cc"); 

似乎我的重寫推送方法沒有被調用。而foo變量是ArrayProxy以外的Array的實例。
我打字稿版本:2.3.2
tsconfig.json

{ 
    "compilerOptions": { 
     "emitDecoratorMetadata": true, 
     "experimentalDecorators": true, 
     "moduleResolution": "classic", 
     "target": "es5", 
     "module": "system", 
     "outFile": "js/test.js" 
    } 
} 

MyTest的
我找了一些解決方案,但失敗了。

class MyNewArray<T> extends Array<T> { 
    getFirst() { 
     return this[0]; 
    } 
} 

var myArray = new MyNewArray<string>(); 
myArray.push("First Element"); 
console.log(myArray.getFirst()); // "First Element" 
David Sherret

,但我得到的錯誤。

Uncaught (in promise) Error: myArray.getFirst is not a function 
    Evaluating http://localhost:8080/application/test/application/ts/bind_test 
    Loading application/ts/bind_test 
    at Object.execute (test.js:1733) 
    at j (system.js:4) 
    at E (system.js:4) 
    at O (system.js:4) 
    at system.js:5 

更新 它工作時,我在ArrayProxy的構造函數的超級調用後添加Object.setPrototypeOf(this, ArrayProxy.prototype);。感謝@Aluan Haddad。

回答