我试图创建一个属性的获取和设置方法:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
设置值的关键字是什么?
我试图创建一个属性的获取和设置方法:
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
设置值的关键字是什么?
当前回答
下面是一个工作示例,可以为你指明正确的方向:
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
JavaScript中的getter和setter只是普通的函数。setter是一个接受参数的函数,该参数的值就是被设置的值。
其他回答
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构建工具的配置添加标志。你可以在这里看到:
这将使用ECMAScript 5 Object.defineProperty()特性生成这个JavaScript。
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
你可以这样写
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;
}
}
它非常类似于创建常用方法,只需在开头放置关键字reserved get或set。
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();
在这种情况下,你可以在get getMethod1(){中跳过返回类型
get getMethod1() {
return this._name;
}
根据您所展示的示例,您希望通过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>
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';