Jac*_*obE 21 html javascript class function
JavaScript中是否有最佳实践或常用方法将类成员作为事件处理程序?
考虑以下简单示例:
<head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
事件处理程序buttonClicked被调用,但_clickCount成员不可访问,或这指出了一些其他对象.
关于这类问题的任何好的提示/文章/资源?
paw*_*wel 25
ClickCounter = function(buttonId) {
this._clickCount = 0;
var that = this;
document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
Run Code Online (Sandbox Code Playgroud)
编辑差不多10年后,使用ES6,箭头功能和类属性
class ClickCounter {
count = 0;
constructor( buttonId ){
document.getElementById(buttonId)
.addEventListener( "click", this.buttonClicked );
}
buttonClicked = e => {
this.count += 1;
console.log(`clicked ${this.count} times`);
}
}
Run Code Online (Sandbox Code Playgroud)
https://codepen.io/anon/pen/zaYvqq
直接附加到onclick属性的函数将具有this
指向元素的执行上下文属性.
当你需要一个元素事件来对象的特定实例(在.NET中作为委托)运行时,你需要一个闭包: -
function MyClass() {this.count = 0;}
MyClass.prototype.onclickHandler = function(target)
{
// use target when you need values from the object that had the handler attached
this.count++;
}
MyClass.prototype.attachOnclick = function(elem)
{
var self = this;
elem.onclick = function() {self.onclickHandler(this); }
elem = null; //prevents memleak
}
var o = new MyClass();
o.attachOnclick(document.getElementById('divThing'))
Run Code Online (Sandbox Code Playgroud)
我不知道为什么Function.prototype.bind
这里没有提到。所以我就把这个留在这里;)
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用粗箭头语法,它绑定到函数的词法范围
function doIt() {
this.f = () => {
console.log("f called ok");
this.g();
}
this.g = () => {
console.log("g called ok");
}
}
Run Code Online (Sandbox Code Playgroud)
之后你可以尝试
var n = new doIt();
setTimeout(n.f,1000);
Run Code Online (Sandbox Code Playgroud)
你可以在babel上尝试一下,或者如果你的浏览器支持jsFiddle上的 ES6 的话。
不幸的是,ES6 Class 语法似乎不允许创建词法绑定到 this 的函数。我个人认为也可以这样做。编辑:似乎有实验性的 ES7 功能允许它。