Typescript 获取并设置打字脚本
我正在尝试为属性创建get和set方法:Typescript 获取并设置打字脚本,typescript,Typescript,我正在尝试为属性创建get和set方法: private _name: string; Name() { get: { return this._name; } set: { this._name = ???; } } 设置值的关键字是什么?下面是一个工作示例,它应该为您指明正确的方向: class Foo { _name; get Name() { return this._n
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
设置值的关键字是什么?下面是一个工作示例,它应该为您指明正确的方向:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
JavaScript中的getter和setter只是普通函数。setter是一个函数,它接受一个参数,该参数的值就是要设置的值。您可以编写此函数
class Human {
private firstName : string;
private lastName : string;
constructor (
public FirstName?:string,
public LastName?:string) {
}
get FirstName() : string {
console.log("Get FirstName : ", this.firstName);
return this.firstName;
}
set FirstName(value : string) {
console.log("Set FirstName : ", value);
this.firstName = value;
}
get LastName() : string {
console.log("Get LastName : ", this.lastName);
return this.lastName;
}
set LastName(value : string) {
console.log("Set LastName : ", value);
this.lastName = value;
}
}
TypeScript使用与ActionScript3类似的getter/setter语法
class foo {
private _bar: boolean = false;
get bar(): boolean {
return this._bar;
}
set bar(value: boolean) {
this._bar = value;
}
}
这将使用ECMAScript 5Object.defineProperty()
功能生成此JavaScript
var foo = (function () {
function foo() {
this._bar = false;
}
Object.defineProperty(foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (value) {
this._bar = value;
},
enumerable: true,
configurable: true
});
return foo;
})();
所以用它,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
但是,为了使用它,必须确保TypeScript编译器以ECMAScript 5为目标。如果您正在运行命令行编译器,请像这样使用--target
标志
tsc --target ES5
如果您使用的是Visual Studio,则必须编辑项目文件以将标记添加到TypeScriptCompile生成工具的配置中。你可以看到:
正如@DanFromGermany在下面所建议的,如果您只是简单地读写一个本地属性,比如
foo.bar=true
,那么拥有一个setter和getter对就太过分了。如果需要在读取或写入属性时执行某些操作(如日志记录),则始终可以在以后添加它们 Ezward已经提供了一个很好的答案,但我注意到其中一条评论询问如何使用它。对于像我这样偶然发现这个问题的人,我认为在Typescript网站上有一个关于getter和setter的官方文档的链接会很有用,因为这很好地解释了这一点,希望在进行更改时始终保持最新,并显示了示例用法:
特别是,对于那些不熟悉它的人,请注意不要将“get”一词合并到对getter的调用中(对于setter也是如此):
var myBar=myFoo.getBar();//错
var myBar=myFoo.get('bar');//错误的
您只需执行以下操作:
var myBar=myFoo.bar;//正确(得到)
myFoo.bar=true;//正确(设置)(false显然是正确的!)
给定一个类,如:
class-foo{
private _bar:boolean=false;
get bar():布尔值{
把这个还给我;
}
设置栏(theBar:boolean){
这个。_bar=theBar;
}
}
然后,将调用专用“\u bar”属性的“bar”getter。这与创建常用方法非常相似,只需将关键字reserved
get
或set
放在开头
class Name{
private _name: string;
getMethod(): string{
return this._name;
}
setMethod(value: string){
this._name = value
}
get getMethod1(): string{
return this._name;
}
set setMethod1(value: string){
this._name = value
}
}
class HelloWorld {
public static main(){
let test = new Name();
test.setMethod('test.getMethod() --- need ()');
console.log(test.getMethod());
test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
console.log(test.getMethod1);
}
}
HelloWorld.main();
在这种情况下,您可以跳过
get getMethod1(){
get getMethod1() {
return this._name;
}
我想我可能明白了为什么会如此混乱。在您的示例中,我们需要
\u name
的getter和setter。但我们通过为不相关的类变量name
创建getter和setter来实现这一点
考虑这一点:
class Car {
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount;
}
set yourCarTiresCount(count) {
alert('You shouldn\'t change car tire count')
}
}
上述代码包含以下内容:
get
和set
为yourCarTiresCount
创建getter和setter(不用于tiresCount
)function () {
return this.tiresCount;
}
function (count) {
alert('You shouldn\'t change car tire count');
}
设定者是:
function () {
return this.tiresCount;
}
function (count) {
alert('You shouldn\'t change car tire count');
}
也就是说,每次我们做newcar()。你的cartirescount
,getter就会运行。而对于每一辆newcar()。你的cartirescount('7')
setter就会运行
tireCount
创建getter,而不是setter如果您正在使用TypeScript模块并试图添加导出的getter,则可以执行以下操作:
//dataStore.ts
export const myData:string=undefined;//仅用于输入支持
让_myData:string;//用于记忆getter结果
Object.defineProperty(这是“myData”{
获取:():字符串=>{
如果(_myData==未定义){
_myData=“我的数据”;//假装这花了很长时间
}
返回我的数据;
},
});
然后,在另一个文件中,您有:
import*作为“/dataStore”中的数据存储
console.log(dataStore.myData);/“我的数据”
TS提供了getter和setter,它们允许对象属性在对象外部对如何访问(getter)或更新(setter)有更多的控制。不直接访问或更新属性,而是调用代理函数
示例:
class Person {
constructor(name: string) {
this._name = name;
}
private _name: string;
get name() {
return this._name;
}
// first checks the length of the name and then updates the name.
set name(name: string) {
if (name.length > 10) {
throw new Error("Name has a max length of 10");
}
this._name = name;
}
doStuff () {
this._name = 'foofooooooofoooo';
}
}
const person = new Person('Willem');
// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();
// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';
如果您正在寻找在任何对象(非类)上使用get和set的方法,
Proxy
可能有用:
注意:请注意,这是旧浏览器不支持且必需的新api。根据您展示的示例,您希望通过get()传递数据对象并获取该对象的属性。为此,您需要使用泛型类型,因为数据对象是泛型的,可以是任何对象
export class Attributes<T> {
constructor(private data: T) {}
get = <K extends keyof T>(key: K): T[K] => {
return this.data[key];
};
set = (update: T): void => {
// this is like spread operator. it will take this.data obj and will overwrite with the update obj
// ins tsconfig.json change target to Es6 to be able to use Object.assign()
Object.assign(this.data, update);
};
getAll(): T {
return this.data;
}
}
注意这个语法
<K extends keyof T>
为了能够使用它,我们应该注意两件事:
1-在类型中,字符串可以是类型
2-javascript中的所有对象属性本质上都是字符串
当我们使用get()时,它接收的参数类型是传递给构造函数的对象的属性,并且由于对象属性是字符串,并且字符串可以是typescript中的类型,因此我们可以使用此
为什么在构造函数中使用public?是的,在此代码中不能有public in构造函数。public
此处定义了重复的members.您可以编写它,但它不会编译。在诸如get和set之类的属性中使用Pascal大小写可以吗?您可以提供资源或文档来增强这种做法吗?它对我不起作用,在set和get中使用大写字母大小写,它无法识别。要清楚,属性、getter和setter不需要是静态的但是,我们仍然是静态的。Foo.\u name
应该替换为this.\u name
回答得很好。另外,请注意,与C#不同,属性当前没有在TypeScript(v0.9.5)中虚拟化。当您在派生类中实现“get bar()”时,您正在替换“get bar()”在parent.implements中,包括无法从deriv调用基类访问器