前回、こういうコードを書いた。
var Person = function(living, age, gender) {
'use strict';
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() { return this.gender; };
};
var cody = new Person(true, 33, 'male');
console.log(cody);
var bob = new Object();
bob.gender = 'zombie';
bob.age = '153';
bob.getLiving = function() {
return this.living;
};
bob.living = false;
console.log(bob);
$ node prop.js
Person { living: true, age: 33, gender: 'male', getGender: [Function] }
{ gender: 'zombie', age: '153', getLiving: [Function], living: false }
codyの方は”Person”と表示されるが、bobの方は何も表示されない。
bobは”Object”と表示されてもいいんじゃないだろうか?
あるいは、何かが足りないから表示されないのだろうか。
本では、実行環境によってオブジェクト型の表示が変わるとは書いてあるのだが、何を見て表示しているのかは書いていない。
ありそうなのは、コンストラクタだろう。
cody.constructorとbob.constructorをconsole.log()してみよう。
[Function: Person]
[Function: Object]
Objectの場合は表示しない、というルールかもしれない。
var Person = function(living, age, gender) {
'use strict';
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() { return this.gender; };
};
var cody = new Person(true, 33, 'male');
console.log(cody);
var bob = new Object();
bob.gender = 'zombie';
bob.age = '153';
bob.getLiving = function() {
return this.living;
};
bob.living = false;
bob.constructor = cody.constructor;
console.log(bob);
$ node prop.js
Person { living: true, age: 33, gender: 'male', getGender: [Function] }
Person {
gender: 'zombie',
age: '153',
getLiving: [Function],
living: false,
constructor: [Function: Person]
}
うむ、予想したとおりだ。
var Person = function(living, age, gender) {
'use strict';
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() { return this.gender; };
};
var cody = new Person(true, 33, 'male');
var bob = new Object();
bob.gender = 'zombie';
bob.age = '153';
bob.getLiving = function() {
return this.living;
};
bob.living = false;
cody.constructor = function Yoshio(){};
console.log(cody);
console.log(bob);
$ node prop.js
Yoshio {
living: true,
age: 33,
gender: 'male',
getGender: [Function],
constructor: [Function: Yoshio]
}
{ gender: 'zombie', age: '153', getLiving: [Function], living: false }
関数を設定すると、関数名がそのまま出力されるようだ。
まあ、コンストラクタは最初しか使われないはずだから、どうでもよいのかもしれん。
0 件のコメント:
コメントを投稿
コメントありがとうございます。
スパムかもしれない、と私が思ったら、
申し訳ないですが勝手に削除することもあります。
注: コメントを投稿できるのは、このブログのメンバーだけです。