无法访问其他功能中的功能

时间:2015-05-08 08:00:27

标签: javascript

我声明了两个函数:

var vec = function(x,y){
    this.x = x;
    this.y = y;
};
var ray = function(start,end){
    this.origin = start;
    this.direction = end;
};

canvas.onmousemove事件中,我想将这些函数用作对象:

canvas.onmousemove = function(event){
  var ray = new ray(new vec(center_x,center_y), new vec(2,10));
};

但是我的浏览器告诉我函数未定义

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为变量名称ray)与函数名称ray

相同

在此行中更改ray变量名称

 var ray = new ray(new vec(center_x,center_y), new vec(2,10));

使用其他名称,例如rayInstance有意义的名称将为您的未来提供帮助。

var rayInstance = new ray(new vec(center_x, center_y), new vec(2, 10));



var vec = function(x,y){
    this.x = x;
    this.y = y;
};
var ray = function(start,end){
    this.origin = start;
    this.direction = end;
};
  
var center_x =0, center_y=0;
(function() {
   var rayInstance = new ray(new vec(center_x, center_y), new vec(2, 10));
   alert(rayInstance.direction.x + " " + rayInstance.direction.y);
})();