JS-コンストラクタの種類
// 関数宣言文
// 巻き上げあり
function Func(a, b) {
this.a = a;
this.b = b;
}
Func.prototype.show = function() {
console.log(this.a + this.b);
}
// 関数リテラル
Func = function(a, b) {
this.a = a;
this.b = b;
}
Func.prototype.show = function() {
console.log(this.a + this.b);
}
// クラス宣言文
// ES6
// Class Func {
// constructor(a, b) {
// this.a = a;
// this.b = b;
// }
// show() {
// console.log(this.a + this.b);
// }
// }
// クラス式
// ES6
// var Func = class {
// constructor (a, b) {
// this.a = a;
// this.b = b;
// }
// show() {
// console.log(this.a + this.b);
// }
// }
// function Func()
// コンストラクタのアクセッサプロパティ
function Person(name) {
Object.defineProperty(this, 'name', {
get: function() {
return 'Hello ' + name;
},
set: function(newName) {
name = newName.toUpperCase();
},
enumerable: true,
configurable: true
});
}
Person.prototype.sayName = function() {
console.log(this.name);
}
var p = new Person('Tom');
console.log(p.name);
p.name = 'Bob';
console.log(p.name);
p.sayName();