nodejs和javascript添加属性的不同

1 javascript可以通过setProperty()函数为对象添加属性。但是nodejs添加报错。TypeError: channel.setProperty is not a function

const events = require('events');

const net = require('net');

class Channel extends events.EventEmitter{

    constructor(){

        super();

        this.clients = {};

        this.subscriptions={};

    }

}

const channel = new events.EventEmitter();

channel.setProperty('clients',{});

channel.setProperty('subscriptions',{});

channel.on('join',function abc(id,client){

    console.log('this.constructor=',this.constructor);

    this.clients[id] = client;

    this.subscriptions[id] = (clientId,msg) => {

        if(id != clientId){

            this.clients[id].write(msg);

        }

    }

    this.on('broadcast',this.subscriptions[id]);

})

net.createServer( client => {

    const id = `${client.remoteAddress}:${client.remotePort}`;

    channel.emit('join', id, client);

    client.on('data',data => {

        const msg = data.toString();

        channel.emit('broadcast',id,msg);

    })

}).listen(8888);

2 javascript可以通过prototype添加属性,但是nodejs报错。TypeError: Cannot set property 'clients' of undefined

const events = require('events');

const net = require('net');

class Channel extends events.EventEmitter{

    constructor(){

        super();

        this.clients = {};

        this.subscriptions={};

    }

}

const channel = new events.EventEmitter();

channel.prototype.clients = {};

channel.prototype.subscriptions = {};

channel.on('join',function abc(id,client){

    console.log('this.constructor=',this.constructor);

    this.clients[id] = client;

    this.subscriptions[id] = (clientId,msg) => {

        if(id != clientId){

            this.clients[id].write(msg);

        }

    }

    this.on('broadcast',this.subscriptions[id]);

})

net.createServer( client => {

    const id = `${client.remoteAddress}:${client.remotePort}`;

    channel.emit('join', id, client);

    client.on('data',data => {

        const msg = data.toString();

        channel.emit('broadcast',id,msg);

    })

}).listen(8888);

3 直接针对对象添加属性,不报错

const events = require('events');

const net = require('net');

const channel = new events.EventEmitter();

channel.clients = {};

channel.subscriptions = {};

channel.name='zjz';

channel.on('join',function(id,client) {

    console.log('this.name=',this.name);

})

net.createServer( client => {

    const id = `${client.remoteAddress}:${client.remotePort}`;

    channel.emit('join', id, client);

    client.on('data',data => {

        const msg = data.toString();

        channel.emit('broadcast',id,msg);

    })

}).listen(8888);//可以正常运行。

你可能感兴趣的:(nodejs和javascript添加属性的不同)