我在 PaperScript 中创建了两类对象:Node
和 Line
。每条 Line 都有一个 this.nodes 属性,它是一个引用两个 Node 对象的数组,每个 Node 对象代表该行的每一端。节点有一个 this.dragging
属性,该属性在创建 Node 对象时初始化为 false
,但在 上设置为
事件并在 true
onMouseDownonMouseUp
处设置回 false
。这样我就可以跟踪节点是否在某个时间点移动。
现在我希望能够从 Line
对象检查其关联的节点是否在任何时间点被拖动。为此,我有一个 if 语句来检查是否 (this.nodes[0].dragging == true || this.nodes[1].dragging == true)
。如果返回 true,则可以采取进一步的行动。
问题是,无论我是否拖动节点,两个 this.nodes[i].dragging
总是返回 false。为什么会出现这种情况?特别是当我从 Node
对象中检查 this.dragging
的值时,它会在拖动时返回正确的值 true ,否则返回 false 。
编辑包括一些代码:
以下是我的代码的精简版本。重要的一点是 this.dragging
变量。
function Node(pos) {
///// Stuff
this.dragging = false;
this.node.onMouseDown = function(event) {
this.dragging = true;
// Do other stuff
}
this.node.onMouseDrag = function(event) {
if (this.dragging == true) {
// Do stuff
}
}
this.node.onMouseUp = function(event) {
// Do stuff
this.dragging = false;
}
}
以下是 Line 对象的构造函数(部分):
function Line(p1, p2) {
this.nodes = [p1, p2];
///// Stuff
this.update = function() {
if (this.nodes[0].dragging === true || this.nodes[1].dragging === true) {
// True
} else {
// False
}
}
}
第二个编辑评论者询问我如何实例化这些对象:
我按如下方式实例化它们:
var nodeNum = 7;
var lineConnections = [{
from: 0,to: 1}
,{from: 0,to: 2}
,{from: 0,to: 3}
,{from: 0,to: 4}
,{from: 1,to: 2}
,{from: 1,to: 5}
,{from: 2,to: 3}
,{from: 2,to: 4}
,{from: 3,to: 5}
,{from: 4,to: 5}
,{from: 2,to: 5}
]
function init() {
for (var i = 0; i < nodeNum; i++) {
Nodes[i] = new Node();
}
for (var i = 0; i < lineConnections.length; i++) {
Lines[i] = new Line(Nodes[lineConnections[i].from], Nodes[lineConnections[i].to]);
}
}
init();
可通过 http://aronadler.com/experiment/ 获取现场演示
最佳答案
我认为问题在于 this
(如以下代码中的 this.dragging
)引用的是全局对象(窗口),而不是您创建的对象。
this.node.onMouseDown = 函数(事件){
this.dragging = true;
//做其他事情
}
this.node.onMouseDrag = 函数(事件){
if (this.dragging == true) {
//做东西
}
}
this.node.onMouseUp = 函数(事件){
//做东西
this.拖动=假;
}
您可以通过查看全局变量拖动来检查是否已创建。我无法真正修改您的代码,除非它位于 fiddle 或其他易于使用的位置,但您应该能够通过将每个鼠标处理函数绑定(bind)到此来修复它,如下所示:
this.node.onMouseUp = 函数(事件){
//做东西
this.拖动=假;
}.绑定(bind)(这个)
或者通过创建一个不会改变的本地引用的闭包,如下所示:
self = this;
然后从函数中引用 self
,而不是 this
。
关于javascript - 尝试从另一个对象访问对象属性总是返回该属性的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204561/