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);
}