node 对象属性的定义必须满足的条件

示例代码

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属性了。

综上,定义对象的属性必须满足两点:

1. 必须使用this定义
2. 必须初始化
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值