简体   繁体   中英

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

Calling a function from a button is easy in 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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