private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
즉 같은 구문을 사용하여 타입스크립트 getter / setter ActionScript3.
class foo {
private _bar: boolean = false;
get bar(): boolean {
return this._bar;
}
set bar(value: boolean) {
this._bar = value;
}
}
Ecma 스크립트 () 이 JavaScript 를 사용하여 만들 수 있는 5 오브ject.데페인프로페티 피쳐입니다.
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;
})();
그래서 바로 사용할 수 있어,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
그러나 전혀 사용하기 위해, 타입스크립트 컴파일러와의 ECMAScript5 타겟으로의 해야 합니다. 컴파일러 플래그를 사용하여 실행할 경우 명령행을 공략하십시오 이렇게.
대상 ES5 츠
Visual Studio 를 변경하십시오 합니다 사용할 경우 프로젝트 파일 추가 구성에 대한 플래깅 메리 피스크리프트콤필레 대한 구축하십시오 목석같은놈. Here 것을 볼 수 있습니다.
아래와 같은 단지 같은 경우 로컬 @DanFromGermany 제안됩니다 읽기 및 쓰기 속성을 갖는 setter 와 getter 페어당 푸실바 = true 이면 오버킬 있다. 넌 언제나 같은 일을 할 경우, 나중에 추가할 때마다 읽어옵니다 로깅하기 속성 또는 씁니다.
하지만 난 이미 제공된 스워드 좋은 점에 의견을 묻는 질문에 사용 방법 중 하나이다. 나 같은 사람이 될 수 있다고 자신하고 구현하므로 생각해봤죠 누가 이 질문에 대한 공식 문서 링크를 가질 수 있는 유용한 게터 및 세터 잘 할 수 있기를 바랍니다 항상 최신 웹 사이트로 타입스크립트 설명하는 내용이 변경되면 논의하고, 사용 예시:
http://www.typescriptlang.org/docs/handbook/classes.html
특히 잘 모르는 사람들을 위해 t # 39, & # 39 라는 단어는, 리포트가 don& 병합합니다 get& # 39;; 붙여넣습니다 맞추기바인딩 호출하십시오 getter (그리하여 대한 세터): <! - 모든 언어: > ts 랭 -;
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;
}
}
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
정상적인 기능을 JavaScript 에서 세터 게터 및 불과합니다. 기능이 필요한 값이 매개변수입니다 할당 값을 설정할 수 있다.
이 작성할 수 있습니다.
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;
}
}
일반적인 방법은 만드는 것은 매우 유사한, 간단히 말해 '키워드' 또는 '세트' 스케줄됨 확보하십시오 처음부터.
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();
이 경우 얻을 수 있는 'getMethod1 건너띄기 반환 유형' () {
get getMethod1() {
return this._name;
}
아마 내가 생각하는 게 왜 이토록 확보하십시오 혼란스럽다. 예를 들어, 우리는 '에 대한 _name 그들이성년에 게터 및 세터'. 하지만 우리는 만들어 달성하기 위한 게터 및 세터 연관해제된 클래스 변수 '이름'.
이러한 측면에서 볼 때:
class Car{
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount ;
}
set yourCarTiresCount(count) {
alert('You shouldn't change car tire count')
}
}
위 코드를 높여줍니까 다음과 같다.
이 getter 입니다.
function() {
return this.tiresCount ;
}
그리고 세터 입니다.
function(count) {
alert('You shouldn't change car tire count');
}
즉, 우리가 매번 신차 () ',' 실행하십시오 지유르카르티레스카운트 getter 런입니다. 및 각 지유르카르티레스카운트 (& # 39, 7& # 39;) 자동차 () '새' setter 런입니다.
, 간접적으로 getter 만들 수 없지만, 2. '에 대한 민간 타이어카운트 세터'.
TS 는 어떻게 할 수 있는 속성 및 세터 게터 객체에는 더 집중식으로 액세스됩니다 (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';
타입스크립트 작업하는 경우 모듈 및 노력하고 있는 이 같은 일이 내보내집니다 getter 추가하기에서는 수행할 수 있습니다.
<! - 모든 언어: 타입스크립트 - >.
// 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;
},
});
그런 다음, 다른 파일 있습니다.
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"