![](/img/trans.png)
[英]Javascript: How do you call a variable function inside a prototype class?
[英]javascript object - how to call class variable inside class function
我想在用戶點擊div時調用變量“info”
應該打印“成功”的代碼
但它的印刷品“未定義”
HTML
<div id="container" style="width: 100px; height: 100px; border: solid black 1px">
JavaScript的
window.onload = function(){
var Controller = function(){
this.info = ' success ';
this.listener = function(){
alert( this.info );
}
this.set = function( ele ){
ele.onclick = this.listener;
}
}
var target = document.getElementById('container');
var controller = new Controller();
controller.set( target );
}
我的目標
我的問題是在函數“listener”中,
關鍵字“this”是指div元素,而不是類Controller
如何在函數“ listener ”中調用變量信息?
嘗試
var Controller = function(){
var self = this; // Add this
this.info = ' success ';
this.listener = function(){
alert( self.info ); // Modify here
}
....
您可以使用bind
的功能結合到右側this
:
ele.onclick = this.listener.bind(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.