JavaScript对象和其中创建的元素之间的关系是什么?

JavaScript对象和其中创建的元素之间的关系是什么?,javascript,addeventlistener,createelement,Javascript,Addeventlistener,Createelement,是否可以将this.brother作为变量传递给this.son的eventListener function Object(a){ this.brother = a; this.son = document.createElement("div"); document.getElementById('parent').appendChild(this.son); this.son.addEventListener('mousedown',function(){ onM

是否可以将this.brother作为变量传递给this.son的eventListener

function Object(a){
  this.brother = a;
  this.son = document.createElement("div");
  document.getElementById('parent').appendChild(this.son);
  this.son.addEventListener('mousedown',function(){ 
    onMouseDown(event,this.brother);
  });
}
用户输入稍后会更改this.brother的值,因此我不能只传递输入变量a
每次此brother的值更改时,是否必须添加新的eventListener

我不建议这样做,但您可以使用绑定函数:

function _Object(a){ //this is not a great function name
  this.brother = a;
  this.son = document.createElement("div");
  document.getElementById('parent').appendChild(this.son);
  this.son.addEventListener('mousedown',(function(event){ 
    onMouseDown(event,this.brother);
  }).bind(this));
}
this.son.addEventListener('mousedown', (function() { 
  onMouseDown(event, this.brother);
}).bind(this));

至于你的问题,不,你不必更新它。这是指_对象,如果brother指针更改,this.brother将指向新的brother。

你的问题基本上归结为关键字
this
在函数中的含义。有三种选择

1。“适当”功能

this.son.addEventListener('mousedown', function() { 
  onMouseDown(event, this.brother);
});
如果使用完整的函数定义语法定义函数,
function(){}
,则
将引用调用函数的对象。
对于事件侦听器,它是您定义侦听器的对象,在您的情况下,它是您创建的
div
。这意味着您将得到一个错误,因为
div
元素没有名为
brother
的属性

2。箭头功能

this.son.addEventListener('mousedown', function() { 
  onMouseDown(event, this.brother);
});
近年来引入了箭头函数,并使用了不同的语法:

this.son.addEventListener('mousedown', () => { 
  onMouseDown(event, this.brother);
});
箭头函数在各个方面都与“适当”函数完全相同,但有一个例外:它们没有自己的
this
,即
this
将引用它在定义函数的范围内引用的任何对象。
在您的情况下,它将引用您在
对象()中初始化的对象
功能。这可能就是你想要的

(旁注:你真的不应该给你的函数命名为
对象
,这个名字已经被JavaScript中所有对象的基类使用了。重写它会引起各种各样的麻烦)

3。绑定函数

this.son.addEventListener('mousedown', function() { 
  onMouseDown(event, this.brother);
});
JavaScript中的函数是对象,因此它们也有方法。其中之一是
bind()
,它允许您创建函数的绑定副本:

function _Object(a){ //this is not a great function name
  this.brother = a;
  this.son = document.createElement("div");
  document.getElementById('parent').appendChild(this.son);
  this.son.addEventListener('mousedown',(function(event){ 
    onMouseDown(event,this.brother);
  }).bind(this));
}
this.son.addEventListener('mousedown', (function() { 
  onMouseDown(event, this.brother);
}).bind(this));

绑定函数的工作方式也类似于“正确”函数,除了
将始终引用作为参数传递给
bind()
的对象。在使用arrow函数之前,绑定函数通常是确保
始终引用范围内相同对象的最广泛的方法。在arrow函数出现后,它们开始不受欢迎,因为arrow函数效率更高,生成的代码可读性更强。

您的问题有点不清楚,而且提供的代码似乎不起作用,您能用一个简单的代码重写您的问题吗?我主要指的是
这个
组件,以及您希望这些组件在未来如何变化,还有一个名为
Object
的函数只是在问问题。尽管我的问题很草率,但答案很好,非常感谢!