简体   繁体   English

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

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

Calling a function from a button is easy in javascript: 在javascript中,从按钮调用函数很容易:

b.onclick = f;

Calling a method from a button can also be done: 也可以通过按钮调用方法:

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

But we want to call a method of our class from a button through another function. 但是我们想通过一个按钮通过另一个函数来调用类的方法。 Is there any way to do this without passing in the original object? 有什么方法可以在不传入原始对象的情况下执行此操作?

Here is the code that does not work. 这是无效的代码。 this.e is interpreted in the context of the button. 这是在按钮的上下文中解释的。

<!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>

Since the flow interrupted you should bind the following 由于流程中断,您应该绑定以下内容

<!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>

Use Function.prototype.bind to change the context of the this keyword to your a instance 使用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