[英]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.bind將this
關鍵字的上下文更改為您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.