Próbuję utworzyć pobrać i ustawić metodę nieruchomości:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
Co jest kluczowe, aby ustawić wartość?
Próbuję utworzyć pobrać i ustawić metodę nieruchomości:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
Co jest kluczowe, aby ustawić wartość?
Maszynopis używa getter / setter składnię jak ActionScript3.
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
Która będzie produkować ten Javascript, korzystając z ECMAScript 5 Object.defineProperty () funkcję.
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;
})();
Więc go używać,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
Jednakże, w celu wykorzystania go w ogóle, należy upewnić się, że ECMAScript5 cele maszynopis kompilatora. Jeśli używasz kompilatora wiersza polecenia, należy --target flagę takiego;
TSC --target ES5
Jeśli używasz programu Visual Studio, musisz edytować plik projektu, aby dodać flagę do konfiguracji dla narzędzia TypeScriptCompile kompilacji. Widać, że tutaj :
Jak @DanFromGermany sugeruje poniżej, jeśli są po prostu czytanie i pisanie lokalną nieruchomości jak foo.bar = true, a następnie mając parę setter i getter jest przesadą. Zawsze możesz dodać je później, jeśli trzeba coś zrobić, jak rejestrowanie, gdy nieruchomość jest odczytywane lub zapisywane.
Ezward dostarczył już dobrą odpowiedź, ale zauważyłem, że jeden z komentarzy pyta, jak jest ona wykorzystywana. Dla ludzi takich jak ja, którzy natkną się to pytanie, myślałem byłoby mieć link do oficjalnej dokumentacji na pobierające i ustawiające na stronie maszynopisu, jak wyjaśnia to dobrze, mam nadzieję, że zawsze zatrzymać się na bieżąco, jak zmiany są się i przedstawia przykład użycia:
http://www.typescriptlang.org/docs/handbook/classes.html
W szczególności dla tych, którzy nie są zaznajomieni z tym, należy pamiętać, że nie zawierają słowa „dostać” do wywołania getter (i podobnie dla ustawiaczy):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
Trzeba po prostu to zrobić:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
biorąc pod uwagę klasę jak:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
wtedy „bar” getter dla prywatnej własności „” _bar zostanie wywołana.
Oto przykład pracy, który powinien wskazać we właściwym kierunku:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
Pobierające i ustawiające w JavaScript są po prostu normalne funkcje. Setter jest funkcją, która przyjmuje parametr, którego wartość jest wartością jest ustawiony.
Jest bardzo podobna do tworzenia wspólnych metod, wystarczy umieścić słowa kluczowego zastrzeżone getlub setna początku.
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();
W tym przypadku można pominąć typ zwracany w get getMethod1() {
get getMethod1() {
return this._name;
}
Można napisać to
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 oferuje pobierające i ustawiające, które pozwalają właściwości obiektu mieć większą kontrolę, w jaki sposób są one dostępne (getter) lub aktualizacji (rozgrywający) na zewnątrz obiektu. Zamiast bezpośredniego dostępu lub aktualizując właściwość funkcja proxy jest tzw.
Przykład:
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';
Myślę, że chyba się dlaczego jest tak mylące. W przykładzie chcieliśmy pobierające i ustawiające dla _name. Ale to osiągnąć poprzez tworzenie pobierające i ustawiające do zmiennej klasy niespokrewnionego Name.
Rozważ to:
class Car{
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount ;
}
set yourCarTiresCount(count) {
alert('You shouldn't change car tire count')
}
}
Powyższy kod wykonuje następujące czynności:
geti setutworzyć getter i setter dla yourCarTiresCount( nie dlatiresCount ).Getter jest:
function() {
return this.tiresCount ;
}
a seter jest:
function(count) {
alert('You shouldn't change car tire count');
}
Czyli, za każdym razem robimy new Car().yourCarTiresCount, getter działa. I dla każdego new Car().yourCarTiresCount('7')tras seter.
tireCount.Jeśli pracujesz z modułami maszynopis i próbują dodać getter, który jest eksportowany, można zrobić coś takiego:
// 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;
},
});
Następnie w innym pliku, który posiada:
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"