get and set in TypeScript
I'm trying to create get and set method for a property:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
What's the keyword to set a value?
Typescript uses getter/setter syntax that is like ActionScript3.
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
That will produce this Javascript, using the Ecmascript 5 Object.defineProperty() feature.
var foo = (function () {
function foo() {
this._bar = false;
}
Object.defineProperty(foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (theBar) {
this._bar = theBar;
},
enumerable: true,
configurable: true
});
return foo;
})();
So to use it,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target flag like this;
tsc --target ES5
If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:
As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.
Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. For people like me who stumble across this question, I thought it would be useful to have a link to the official documentation on getters and setters on the Typescript website as that explains it well, will hopefully always stay up-to-date as changes are made, and shows example usage:
http://www.typescriptlang.org/docs/handbook/classes.html
In particular, for those not familiar with it, note that you don't incorporate the word 'get' into a call to a getter (and similarly for setters):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
You should simply do this:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
given a class like:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
then the 'bar' getter for the private '_bar' property will be called.
Here's a working example that should point you in the right direction:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
Getters and setters in JavaScript are just normal functions. The setter is a function that takes a parameter whose value is the value being set.
链接地址: http://www.djcxy.com/p/40684.html上一篇: TypeScript将字符串转换为数字
下一篇: 在TypeScript中获取并设置