Sto cercando di creare metodi get e set per una proprietà:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
Qual è la parola chiave per impostare un valore?
Sto cercando di creare metodi get e set per una proprietà:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
Qual è la parola chiave per impostare un valore?
Carattere tipografico utilizza la sintassi getter / setter che è come ActionScript3.
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
Che la produzione di questo JavaScript, utilizzando la funzione di ECMAScript 5 Object.defineProperty ().
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;
})();
Quindi, per usarlo,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
Tuttavia, al fine di utilizzare a tutti, è necessario assicurarsi che il target dattiloscritto compilatore ECMAScript5. Se si esegue il compilatore a riga di comando, utilizzare la bandiera --target come questo;
TSC --target ES5
Se si utilizza Visual Studio, è necessario modificare il file di progetto per aggiungere il flag alla configurazione per lo strumento TypeScriptCompile build. Si può vedere che qui :
Come @DanFromGermany suggerisce di seguito, se siete alla semplice lettura e la scrittura di un locale di proprietà come foo.bar = true, quindi avere un paio setter e getter è eccessivo. È sempre possibile aggiungere in un secondo momento, se avete bisogno di fare qualcosa, come la registrazione, ogni volta che la proprietà è letto o scritto.
Ezward ha già fornito una buona risposta, ma ho notato che uno dei commenti chiede come vengono utilizzati. Per chi come me incappare in questo problema, ho pensato che sarebbe stato utile avere un collegamento alla documentazione ufficiale su getter e setter sul sito web tipografico come che spiega bene, si spera sempre rimanere up-to-date, se i cambiamenti sono fatto, e mostra esempio di utilizzo:
http://www.typescriptlang.org/docs/handbook/classes.html
In particolare, per chi non ha familiarità con essa, si noti che non incorporare la parola 'entrare' in una chiamata ad un getter (e allo stesso modo per il setter):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
Si dovrebbe fare semplicemente questo:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
data una classe come:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
poi il getter 'bar' per il '_bar' proprietà privata sarà chiamato.
Ecco un esempio di lavoro che dovrebbe puntare nella giusta direzione:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
Getter e setter in JavaScript sono funzioni normali. Il setter è una funzione che accetta un parametro il cui valore è il valore da impostare.
E 'molto simile alla creazione di metodi comuni, è sufficiente mettere la parola chiave riservata geto setall'inizio.
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();
In questo caso è possibile saltare tipo di ritorno in get getMethod1() {
get getMethod1() {
return this._name;
}
È possibile scrivere questo
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;
}
}
TS offre getter e setter che permettono proprietà degli oggetti di avere un maggiore controllo del modo in cui si accede (getter) o aggiornato (setter) al di fuori dell'oggetto. Invece di direttamente accesso o aggiornare la proprietà una funzione proxy sia chiamato.
Esempio:
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';
Penso che probabilmente ho perché è così confusa. Nel tuo esempio, abbiamo voluto getter e setter per _name. Ma otteniamo che con la creazione di getter e setter per una variabile di classe non correlata Name.
Considerate questo:
class Car{
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount ;
}
set yourCarTiresCount(count) {
alert('You shouldn't change car tire count')
}
}
codice di cui sopra fa seguito:
gete setcreare getter e setter per yourCarTiresCount( non pertiresCount ).Il getter è:
function() {
return this.tiresCount ;
}
e il setter è:
function(count) {
alert('You shouldn't change car tire count');
}
Che significa, ogni volta che facciamo new Car().yourCarTiresCount, getter viene eseguito. E per ogni new Car().yourCarTiresCount('7')run setter.
tireCount.Se si lavora con i moduli dattiloscritto e sta tentando di aggiungere un getter che viene esportato, si può fare qualcosa di simile a questo:
// dataStore.ts
export const myData: string = undefined; // just for typing support
let _myData: string; // for memoizing the getter results
Object.defineProperty(this, "myData", {
get: (): string => {
if (_myData === undefined) {
_myData = "my data"; // pretend this took a long time
}
return _myData;
},
});
Poi, in un altro file si dispone di:
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"