我目前正在摆弄“纯js-page”的创建(没有HTML内容,没有CSS只是JSON提供“构造函数”)并偶然发现了一个我无法解决的问题功能?!
<html>
<head>
<script>
'use strict'
var x = class {
constructor(args) {
console.log('class')
this.a = args[0]
this.b = args[1]
this.c = args[2]
this.d = this.d.bind(this)
this.e = this.e.bind(this)
this.d()
}
}
x.prototype.d = function() {
console.log('listener')
document.getElementById('h').addEventListener('mouseover',this.e,false)
}
x.prototype.e = function() {
console.log('handler')
this.a(this.b)
}
var f = function(args) {
console.log('call: '+args)
console.log(event.target)
}
var g = function(args) {
new x(args)
}
</script>
</head>
<body onload="g([f,'hello',1000]);">
<div id="h" style="width:200px;height:200px;background:grey;">lorem...</div>
</body>
</html>
虽然上面的代码完全按“预期”执行(我不需要单独传递事件对象),但是我无法实现传递事件对象的setTimeout。
<html>
<head>
<script>
'use strict'
var x = class {
constructor(args) {
console.log('class')
this.a = args[0]
this.b = args[1]
this.c = args[2]
this.d = this.d.bind(this)
this.e = this.e.bind(this)
this.d()
}
}
x.prototype.d = function() {
console.log('listener')
document.getElementById('h').addEventListener('mouseover',this.e,false)
}
x.prototype.e = function() {
console.log('handler')
setTimeout(() => {this.a(this.b)},this.c)
}
var f = function(args) {
console.log('call: '+args)
console.log(event.target)
}
var g = function(args) {
new x(args)
}
</script>
</head>
<body onload="g([f,'hello',1000]);">
<div id="h" style="width:200px;height:200px;background:grey;">lorem...</div>
</body>
</html>
箭头函数幸运地摆脱了关于此的完整参考废话,但我在“函数f”中松开了事件引用。
有没有办法达到与上例相同的“状态”?
非常感谢任何帮助,但请注意我是业余爱好者(是的,我做了“google”)并且经过几个小时的阅读范围,应用,绑定,调用,箭头功能(我希望他们会帮助,。 ..好)和其他东西,我仍然找不到合适的解决方案(!jquery&amp;&amp;!node&amp;&amp;!angular&amp;&amp;!typescript&amp;&amp; vanilla)。
问候
答案 0 :(得分:0)
好像你没有传递事件参数this.a(e, this.b)}
。请参阅更新的代码段:
<html>
<head>
<script>
'use strict'
var x = class {
constructor(args) {
console.log('class')
this.a = args[0]
this.b = args[1]
this.c = args[2]
this.d = this.d.bind(this)
this.e = this.e.bind(this)
this.d()
}
}
x.prototype.d = function() {
console.log('listener')
document.getElementById('h').addEventListener('mouseover',this.e,false)
}
x.prototype.e = function(e) {
console.log('handler')
setTimeout(() => {this.a(e, this.b)},this.c)
}
var f = function(event, args) {
console.log('call: '+args)
console.log(event.target)
}
var g = function(args) {
new x(args)
}
</script>
</head>
<body onload="g([f,'hello',1000]);">
<div id="h" style="width:200px;height:200px;background:grey;">lorem...</div>
</body>
</html>