Vue3+TypeScript从入门到精通系列之:读取器和存取器
一、TypeScript读取器和存取器
(() => {
//静态成员:在类中通过static修饰的属性或者方法,就是静态的属性及静态的方法,也称为静态成员
//静态成员在使用的时候通过类名来调用
class Person {
firstName:string
lastName:string
constructor(firstName:string,lastName:string){
this.firstName = firstName
this.lastName = lastName
}
//读取器
get fullName(){
return this.firstName+ '-' + this.lastName
}
//设置器
set fullName(val){
let names = val.split('_')
this.firstName = names[0]
this.lastName = names[1]
}
}
const person: Person = new Person("加油","学习vue3")
console.log(person.fullName)
person.fullName = '诸葛_孔明'
console.log(person.fullName)
})()
二、TypeScript读取器和存取器代码转化为js
编译到版本ES5或以上,不然会报错
tsc ./静态.ts -t es5
(function () {
//静态成员:在类中通过static修饰的属性或者方法,就是静态的属性及静态的方法,也称为静态成员
//静态成员在使用的时候通过类名来调用
var Person = /** @class */ (function () {
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Object.defineProperty(Person.prototype, "fullName", {
//读取器
get: function () {
return this.firstName + '-' + this.lastName;
},
//设置器
set: function (val) {
var names = val.split('_');
this.firstName = names[0];
this.lastName = names[1];
},
enumerable: false,
configurable: true
});
return Person;
}());
var person = new Person("加油", "学习vue3");
console.log(person.fullName);
person.fullName = '诸葛_孔明';
console.log(person.fullName);
})();
三、查看js输出
node ./读取器和存取器.js
加油-学习vue3
诸葛-孔明