TypeScript 屬性裝飾器


/**
 * 屬性裝飾器只能接收到兩個參數
 * @param target Test 對應的 prototype
 * @param key  屬性名字
 */
function nameDecorator(target: any, key: string):any {
  const descriptor: PropertyDescriptor = {
    writable: false
  }

  return descriptor;
}

class Test{ 
  @nameDecorator
  name = '1111'
}

const test = new Test();

// 本身是可以對屬性進行修改的
// test.name = '2222';
// console.log(test.name); // 2222

// 在裝飾器里面加以修飾就可以改變這個局面
test.name = '3333'
console.log(test.name); // 報錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM