ค้นหาเว็บไซต์

รับและตั้งค่าใน TypeScript


ฉันกำลังพยายามสร้างเมธอด get และ set สำหรับคุณสมบัติ:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

คีย์เวิร์ดสำหรับตั้งค่าคืออะไร?

คำตอบ #1

TypeScript ใช้ไวยากรณ์ getter/setter ที่คล้ายกับ ECMAScript4/ActionScript3

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

อย่างไรก็ตาม เพื่อที่จะใช้มันได้ คุณต้องแน่ใจว่าโปรแกรมคอมไพเลอร์ TypeScript ตั้งค่าเป้าหมายเป็น ECMAScript5 หรือสูงกว่า หากคุณกำลังใช้คอมไพเลอร์ผ่านบรรทัดคำสั่ง ให้ใช้แฟลก --target ดังนี้:

tsc --target ES5

หากคุณกำลังใช้ Visual Studio คุณต้องแก้ไขไฟล์โครงการของคุณเพื่อเพิ่มธงไปยังการกำหนดค่าสำหรับเครื่องมือสร้าง TypeScriptCompile คุณสามารถดูได้ที่นี่:

นั่นจะสร้าง JavaScript นี้ โดยใช้คุณสมบัติ Object.defineProperty() ของ ECMAScript 5

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;
})();

เวอร์ชันล่าสุดของ EcmaScript จะสร้างโค้ดที่ดูเหมือนกับ TypeScript ดั้งเดิมมากขึ้น ตัวอย่างเช่น การตั้งเป้าไปที่ EcmaScript2017 จะสร้าง:

"use strict";
class foo {
    constructor() {
        this._bar = false;
    }
    get bar() {
        return this._bar;
    }
    set bar(value) {
        this._bar = value;
    }
}

ดังนั้นในการใช้งานมัน,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

ตามที่ @DanFromGermany แนะนำด้านล่าง ถ้าคุณเพียงแค่กำลังอ่านและเขียนคุณสมบัติท้องถิ่น เช่น foo.bar=true การมีคู่ setter และ getter ถือว่าเกินความจำเป็น คุณสามารถเพิ่มพวกมันทีหลังได้เสมอถ้าคุณต้องการทำบางสิ่งบางอย่าง เช่น การบันทึกทุกครั้งที่มีการอ่านหรือเขียนคุณสมบัติ

Getter สามารถใช้เพื่อสร้างคุณสมบัติแบบอ่านอย่างเดียว นี่คือตัวอย่างที่แสดงด้วยว่า getter ทำงานร่วมกับชนิดอ่านอย่างเดียวและชนิดตัวเลือกอย่างไร

//
// type with optional readonly property.
// baz?:string is the same as baz:string|undefined
//
type Foo = {
    readonly bar: string;
    readonly baz?: string;
}
const foo:Foo = {bar: "bar"}
console.log(foo.bar) // prints 'bar'
console.log(foo.baz) // prints undefined

//
// interface with optional readonly property
//
interface iFoo {
    readonly bar: string;
    readonly baz?: string;
}

const ifoo:iFoo = {bar: "bar"}
console.log(ifoo.bar)  // prints 'bar'
console.log(ifoo.baz)  // prints undefined


//
// class implements bar as a getter, 
// but leaves off baz.
//
class iBarClass implements iFoo {

    get bar() { return "bar" }
}
const iBarInstance = new iBarClass()
console.log(iBarInstance.bar) // prints 'bar'
console.log(iBarInstance.baz) // prints 'undefined'
// accessing baz gives warning that baz does not exist 
// on iBarClass but returns undefined
// note that you could define baz as a getter
// and just return undefined to remove the warning.


//
// class implements optional readonly property as a getter
//
class iBazClass extends iBarClass {
    private readonly _baz?: string

    constructor(baz?:string) {
        super()
        this._baz = baz
    }

    get baz() { return this._baz; }
}

const iBazInstance = new iBazClass("baz")
console.log(iBazInstance.bar)  // prints bar
console.log(iBazInstance.baz)  // prints baz

คำตอบ #2

Ezward ได้ให้คำตอบที่ดีแล้ว แต่ฉันสังเกตว่ามีความคิดเห็นหนึ่งถามว่ามันถูกใช้อย่างไร สำหรับคนที่เหมือนฉันที่พบบทความคำถามนี้บังเอิญ ฉันคิดว่าคงเป็นประโยชน์ที่จะมีลิงก์ไปยังเอกสารอย่างเป็นทางการเกี่ยวกับ getters และ setters ในเว็บไซต์ Typescript เพราะเอกสารนั้นอธิบายได้ดี น่าจะได้รับการอัปเดตอยู่เสมอตามการเปลี่ยนแปลง และแสดงตัวอย่างการใช้งาน:

http://www.typescriptlang.org/docs/handbook/classes.html

โดยเฉพาะอย่างยิ่ง สำหรับผู้ที่ไม่คุ้นเคยกับมัน โปรดทราบว่าคุณไม่ต้องใส่คำว่า 'get' เข้าไปในการเรียกใช้งาน getter (และในทำนองเดียวกันสำหรับ setter)

var myBar = myFoo.getBar(); // wrong    
var myBar = myFoo.get('bar');  // wrong

คุณก็แค่ทำแบบนี้:

var myBar = myFoo.bar;  // correct (get)
myFoo.bar = true;  // correct (set) (false is correct too obviously!)

เมื่อมีคลาสแบบ:

class foo {
  private _bar:boolean = false;

  get bar():boolean {
    return this._bar;
  }
  set bar(theBar:boolean) {
    this._bar = theBar;
  }
}

แล้วตัว getter 'bar' สำหรับ property ส่วนตัว '_bar' จะถูกเรียกใช้งาน

คำตอบ #3

นี่คือตัวอย่างที่ใช้งานได้ซึ่งควรชี้ทางให้คุณไปในทิศทางที่ถูกต้อง:

class Foo {
    _name;

    get Name() {
        return this._name;
    }

    set Name(val) {
        this._name = val;
    }
}

Getter และ setter ใน JavaScript เป็นเพียงฟังก์ชันปกติ Setter เป็นฟังก์ชันที่รับพารามิเตอร์ซึ่งค่าของมันคือค่าที่ถูกตั้ง

คำตอบ #4

คุณสามารถเขียนสิ่งนี้ได้

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;
    } 

}

บทความที่เกี่ยวข้อง