Node.js本地函数中的未定义变量

时间:2017-02-15 10:18:08

标签: javascript node.js p5.js

我只是想问一下,为什么我的函数变量给出了一个未定义的值,但我正确地为它赋值。这是我的代码。

server.js代码



var express = require('express');

var app = express();

var server = app.listen(process.env.PORT || 3000, listen);

function listen() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://' + host + ':' + port);
}

function asd(width, height){
  this.width = width;
  this.height = height;
}

app.use(express.static('public'));

var io = require('socket.io')(server);

io.sockets.on('connection',

  function (socket) {
  
    console.log("We have a new client: " + socket.id);

    socket.on('display',
      function(data){
        asd(data.width, data.height);
        console.log(asd.width);
      }

      );
    
    socket.on('disconnect', function() {
      console.log("Client has disconnected");
    });
  }
);




sketch.js代码



var circle;
var circles = [];
var zoom = 1;
var newZoom;
var socket;

function setup() {
  socket = io.connect('http://localhost:3000');
  createCanvas(1366, 666);
  circle = new Circle(0, 0, 64);

  var data = {
    width: 1366,
    height: 666
  };

  socket.emit('display', data);

}

function draw() {
  background(60);
  translate(width / 2, height / 2);
  newZoom = (64 / circle.radius*1.5);
  zoom = lerp(zoom, newZoom, 0.1);
  scale(zoom);
  translate(-circle.position.x, -circle.position.y);

  for (var x = circles.length - 1; x >= 0; x--) {
    if (circle.eat(circles[x])) {
      circles.splice(x, 1);
    }
  }

  circle.show();
  circle.update();
  circle.constrain();


  for (var x = 0; x < circles.length; x++) {
    circles[x].show();
  }
}
&#13;
&#13;
&#13;

我试图在控制台日志中直接输出data.width,并且那里有数据。请帮忙。

1 个答案:

答案 0 :(得分:1)

你没有在asd上调用new来创建一个对象。相反,你将它用作基本功能。

试试这个;

socket.on('display',
      function(data){
        var myObject = new asd(data.width, data.height);
        console.log(myObject.width);
      }
);