繁体   English   中英

如何通过按钮在Javascript中调用方法(使用此方法)?

[英]How to call a method (using this) in Javascript from a button?

在javascript中,从按钮调用函数很容易:

b.onclick = f;

也可以通过按钮调用方法:

Myclass.prototype.m = function() {
    var t = this;
    b.onclick = t.f;
}

但是我们想通过一个按钮通过另一个函数来调用类的方法。 有什么方法可以在不传入原始对象的情况下执行此操作?

这是无效的代码。 这是在按钮的上下文中解释的。

<!DOCTYPE html>
<html>
<body>
</body>
<script>
function A() {}
A.prototype.e = function() {
  console.log("bar");
}

A.prototype.f = function() {
  console.log("foo!");
  this.e();
}

A.prototype.g = function() {
  var b = document.createElement("button");
  b.innerHTML = "say foo!";
  b.onclick = this.f;
  document.getElementsByTagName("body")[0].appendChild(b);
}

var a = new A();
a.g();

</script>
</html>

由于流程中断,您应该绑定以下内容

<!DOCTYPE html>
<html>
<body>
</body>
<script>
function A() {}
A.prototype.e = function() {
  console.log("bar");
}

A.prototype.f = function() {
  console.log("foo!");
  this.e();
}

A.prototype.g = function() {
  var b = document.createElement("button");
  b.innerHTML = "say foo!";
  b.onclick = this.f.bind(this)
  document.getElementsByTagName("body")[0].appendChild(b);
}

var a = new A();
a.g();

</script>
</html>

使用Function.prototype.bindthis关键字的上下文更改为您a实例

<!DOCTYPE html>
<html>
<body>
</body>
<script>
function A() {}
A.prototype.e = function() {
  console.log("bar");
}

A.prototype.f = function() {
  console.log("foo!");
  this.e();
}

A.prototype.g = function() {
  var b = document.createElement("button");
  b.innerHTML = "say foo!";
  b.onclick = this.f.bind(this);
  document.getElementsByTagName("body")[0].appendChild(b);
}

var a = new A();
a.g();

</script>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM