/typescript/

TypeScript part 20 (getters and setters)

2017-03-04 19:09:51

TypeScript

class Person {

    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    get name(): string {
        return this._name;
    }

    set name(value: string) {
        this._name = value;
    }
}

let person = new Person("Michał");
console.log(person.name);

person.name = "Adam";

console.log(person.name);

JavaScript

var Person = (function () {
    function Person(name) {
        this._name = name;
    }
    Object.defineProperty(Person.prototype, "name", {
        get: function () {
            return this._name;
        },
        set: function (value) {
            this._name = value;
        },
        enumerable: true,
        configurable: true
    });
    return Person;
}());
var person = new Person("Michał");
console.log(person.name);
person.name = "Adam";
console.log(person.name);

TypeScript

class Person {

    private name: string;

    constructor(name: string) {
        this.name = name;
    }

    public setName(name: string): void {
        this.name = name;
    }

    public getName(): string {
        return this.name;
    }
}

let person = new Person("Michał");
console.log(person.getName());

person.setName("Adam");

console.log(person.getName());

JavaScript

var Person = (function () {
    function Person(name) {
        this.name = name;
    }
    Person.prototype.setName = function (name) {
        this.name = name;
    };
    Person.prototype.getName = function () {
        return this.name;
    };
    return Person;
}());
var person = new Person("Michał");
console.log(person.getName());
person.setName("Adam");
console.log(person.getName());