(发布后不久进行编辑以简化。)
标题不是很具体,我很抱歉,但我不确定要更具体地问什么。
完整的jsfiddle:https://jsfiddle.net/scottbrown0001/byz63qxm/6/
我很困惑为什么下面的代码会产生以下行为:行
d3.select(this).select('.here').text(name);
将 name
的预期值“Foo 1”和“Foo 2”放置在两个 div 中的每一个中,但该行
d3.select(this).select('.there').text(thisFoo.name);
始终在两个 div 中放置相同实例的名称
。
很明显,这是一个范围问题或其他问题,但我无法理解它为什么会这样。
<style>
div {margin: 20px; }
.top {margin-top: 40px; }
</style>
</head>
<body>
<div class='top top1'>
<div class='clicker'>
CLICK ME
<div class='here'> HERE </div>
<div class='there'> THERE </div>
</div>
</div>
<div class='top top2'>
<div class='clicker'>
CLICK ME
<div class='here'> HERE </div>
<div class='there'> THERE </div>
</div>
</div>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
d3.selection.prototype.trigger = function(event, detail) {
var e = new CustomEvent(event, detail);
this.node().dispatchEvent(e);
return this;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function Foo(where, name) {
this.name = name;
var top = d3.select('.' + where);
var clicker = top.select('.clicker');
thisFoo = this;
clicker.on(
'click',
function(){
d3.select(this).select('.here').text(name);
d3.select(this).select('.there').text(thisFoo.name);
}
)
}
foo1 = new Foo('top1', 'Foo 1');
foo2 = new Foo('top2', 'Foo 2');
</script>
</body>
</html>
最佳答案
因为你没有使用var
声明时关键字 thisFoo
,您将其设为全局变量:
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.
所以发生的事情是 foo1 = new Foo('top1', 'Foo 1');
行执行后thisFoo
是对新创建的 Foo
的引用目的。以下行foo2 = new Foo('top2', 'Foo 2');
更改全局变量 thisFoo
的值这样它就成为对第二个 Foo
的引用对象。
如果您确保使用var
,您的代码应该按照您想要的方式工作。关键字以确保 thisFoo
绑定(bind)到Foo
的函数范围。
关于javascript 类实例处理事件不一致 - this/范围界定困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942660/