オブジェクトとは「値と処理をひとまとめに保管し、名前で取り出せるようにしたもの」
プロパティ: オブジェクトの中の値
メソッド: オブジェクトの中の関数
同じプロパティやメソッドを使う場合、this. と書く
const person = {
name: "taro",
age: 39,
print: function(): void {
console.log(this.name + '('
+ this.age + ')')
}
}
person.print()
person.name = 'hanako'
person.age = 28
person.print()
### Objectによる生成
const person = Object()
person.name = "taro"
person.age = 39
person.print = function():void {
console.log(this.name + '('
+ this.age + ')')
}
### ファクトリ関数
ファクトリとは値を作成するもの
function Person(n:string, a:number):
{name:string, age:number, print:()=>void}{
return {
name: n,
age: a,
print: function(){
console.log(this.name +
'(' + this.age + ')')
}
}
}
const taro = Person('taro', 39)
const hana = Person('hanako', 28)
taro.print()
hana.print()
### オブジェクトに引数を通過う
type person = {name:string, age:number}
function setData(ob:person, n:string, a:number):person {
ob.name = n
ob.age = a
return ob
}
const ob1:person = {name:'taro', age:39}
const ob2:person = setData(ob1, 'hanako', 28)
console.log(ob1)
console.log(ob2)
### オブジェクトの分割代入
type person = {name:{first:string, second:string}, age:number}
const ob1:person = {name:{first:'taro', second: 'yamada'}, age:39}
const {name:{first, second}, age} = ob1
console.log(first + "-" + second + '::' + age)
### プロパティのオプションとReadonly
type person = {readonly name:string, mail?:string, age?:number, print:()=>void}
const ob1:person = {
name: 'taro',
age: 39,
print:function():void {
console.log(this.name + ':' + this.age)
}
}
const ob2:person = {
name: 'hanako',
mail: 'hanako@gmail.com',
print:function():void {
console.log(this.name + ':' + this.mail)
}
}
ob1.print()
ob2.print()