また、{}のなかに直接対象オブジェクトの属性を指定することができる。
属性と値の間に:を書く、属性と属性の間に,を入れる
// 従来の書き方
var obj = new Object();
// 現在オブジェクト生成するときに使用する主流の書き方
var obj = {
name: "田中さん",
age:40,
gender: "男"
};
// 辞書を取り出す
console.log(Object.values(obj));
// 値を順番に取り出す
for(value of Object.values(obj)){
console.log(value);
}
ユーザー定義関数
例:郵便番号数を確認するユーザー定義関数
const postCode = '123-45678';
function checkPostCode(string){
const replaced = string.replace('-','');
const length = replaced.length;
if(length === 7){
return true;
}
return false;
}
console.log(checkPostCode(postCode));
変数の命名については、JSは大文字と小文字を区別するため、camelCaseを多用しています。
HTML,CSSは大文字と小文字を区別しないため、snake_caseを使います。
オブジェクトの中に値や関数を組み込み
オブジェクトの中の値を使う場合は、thisをつける必要があります。
const post = {
postCode : '123-45678',
checkPostCode(){
const replaced = this.postCode.replace("-","");
const length = replaced.length;
//このように書くこともできる const replaced = this.postCode.replace("-","").length;
if(length==7){
return true;
}
return false;
}
};
console.log(post.checkPostCode());
メソッドチェーンについても簡単に例を書きます。
const person = {
name:'本田',
age: 30,
getName(){
console.log(this.name);
return this;
},
getAge(){
console.log(this.age);
return this;
}
};
// メソッドチェーン
// 1行で二つのメソッドを実行することができる
person.getName().getAge();