typescript存取器和静态属性


let passcode = 'secret password'
//存取器
class Employeer {
   private _fullName: string
   get fullName():string {
     return this._fullName
   }
   set fullName(newName:string) {
     if(passcode === 'secret password') {
       this._fullName = newName
     }else {
       console.log('error, vvvv')
     }
   }
 }

 let p1 = new Employeer()
 p1.fullName = 'Bob'
 if(p1.fullName) {
   console.log(p1.fullName)
 }


 //静态属性--坐标点距离原点的距离
 class Grid {
   static origin = {x:0,y:0}
   scale:number
   constructor(scale:number) {
     this.scale=scale
   }
   //传入坐标点,计算它到原点的距离
   calculateDistanceFromOrigin(point:{x:number,y:number}) {
    let xDist = point.x - Grid.origin.x
    let yDist = point.y - Grid.origin.y
    // 勾股定理
    return Math.sqrt(Math.pow(xDist,2)+Math.pow(yDist,2))
      *this.scale
   }
 }

 let grid1 = new Grid(1.0)
 let grid2 = new Grid(5.0)
 //5
 console.log(grid1.calculateDistanceFromOrigin({
   x: 3,
   y:4,
 }))
 //25
 console.log(grid2.calculateDistanceFromOrigin({
    x: 3,
    y:4,
  }))

以上是学习笔记,除了es6的class类的set和get方法,es5的Object.defineProperty的set和get方法是vue的双向绑定的原理,笔力有限,具体请自行扩展

像以上的存取器部分转化为es5代码为:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var passcode = 'secret password';
//存取器
var Employeer = /** @class */ (function () {
    function Employeer() {
    }
    Object.defineProperty(Employeer.prototype, "fullName", {
        get: function () {
            return this._fullName;
        },
        set: function (newName) {
            if (passcode === 'secret password') {
                this._fullName = newName;
            }
            else {
                console.log('error, vvvv');
            }
        },
        enumerable: true,
        configurable: true
    });
    return Employeer;
}());
var p1 = new Employeer();
p1.fullName = 'Bob';
if (p1.fullName) {
    console.log(p1.fullName);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值