我试图创建一个属性的获取和设置方法:

private _name: string;

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

设置值的关键字是什么?


当前回答

你可以这样写

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

}

其他回答

我想我大概知道为什么这么令人困惑了。在您的示例中,我们需要_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)。

getter是:

function () {
    return this.tiresCount;
}

setter是:

function (count) {
    alert('You shouldn\'t change car tire count');
}

意思是,每次执行new Car()。yourCarTiresCount, getter运行。并且对于每一个新的Car(). yourcartirescount ('7') setter运行。

间接地为私有ti复述创建getter,而不是setter。

如果你正在寻找在任何对象(不是类)上使用get和set的方法,代理可能是有用的: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world

注意:请注意,这是不支持的新api,旧浏览器需要polifill

根据您所展示的示例,您希望通过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;
    }
  }

< T >指泛型类型。让我们初始化一个实例

 const myAttributes=new Attributes({name:"something",age:32})

 myAttributes.get("name")="something"

注意这个语法

<K extends keyof T>

为了能够使用这个,我们应该注意两件事:

1- in typestring字符串可以是一个类型。

2- javascript中所有对象属性本质上都是字符串。

当我们使用get()时,它接收的参数类型是传递给构造函数的对象属性,由于对象属性是字符串,并且字符串在typescript中允许是类型,我们可以使用这个<K extends keyof T>

你可以这样写

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提供了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';