示例代码
var util = require('util');
function Person() {
var sex = '男';
this.name = 'zou'; //必须使用this定义才算属性
this.age = 0; //必须初始化才算属性
this.setName = function(thyName) {
this.name=thyName;
};
this.getName = function() {
return this.name;
}
this.toString = function() {
return this.name;
};
this.say = function() {
console.log(this.name);
}
}
var obj = new Person();
使用util模块的inspect方法打印对象obj的属性
console.log(util.inspect(obj));
PS E:\nodejs\nodetest> node .\object.js
Person {
name: 'jun',
age: 0,
setName: [Function (anonymous)],
getName: [Function (anonymous)],
toString: [Function (anonymous)],
say: [Function (anonymous)]
}
从上面打印结果可以看出,只有使用this定义的变量才算对象的属性,sex变量没有使用this定义。
使用this引用sex并打印结果:
console.log(obj.sex);
PS E:\nodejs\nodetest> node .\object.js
undefined
从打印结果可以看出,sex并不是obj的属性。
使用this定义的变量还必须初始化才能算作对象的属性
将上述代码改为如下,age变量不初始化:
var util = require('util');
function Person() {
var sex = '男';
this.name = 'zou'; //必须使用this定义才算属性
this.age ; //必须初始化才算属性
this.setName = function(thyName) {
this.name=thyName;
};
this.getName = function() {
return this.name;
}
this.toString = function() {
return this.name;
};
this.say = function() {
console.log(this.name);
}
}
var obj = new Person();
打印结果:
console.log(util.inspect(obj));
PS E:\nodejs\nodetest> node .\object.js
Person {
name: 'jun',
setName: [Function (anonymous)],
getName: [Function (anonymous)],
toString: [Function (anonymous)],
say: [Function (anonymous)]
}
会发现打印的结果中没有age属性了。