[英]How to override javascript method and call from class?
打擾一下標題,但我不確定這叫什么(也許是事件?):
我創建了一個班級,有人可以使用:
function cls_something()
{
this.notify('hello');
}
現在,使用我的課程的人創建了一個名為“ notify”的方法(按照我的指示),以便偵聽通知,然后使用我通過的參數執行自己的自定義代碼:
var something = new cls_something();
something.notify = function(message)
{
console.log('The notification is ' + message);
}
如何在類中調用此方法以向他發送通知消息?
我正在努力實現這樣的目標...
websocket = new WebSocket("ws://localhost:10000");
websocket.onopen = function(e)
{
console.log('you are connected');
}
websocket.onmessage = function(e)
{
console.log('omg wtf ffs, there was an error: ' + e.msg);
}
您可以只調用this.notify(“ Message”); 不過,您可能需要檢查是否首先定義了它。
編輯1:
好的,所以這里的問題是您在定義函數之前直接從構造函數中調用了函數。 如果需要在構造函數中定義它,則將該函數作為參數傳遞。
function cls_something(notifyFunction)
{
notifyFunction('hello');
}
編輯2:
只是我們很清楚,您可以根據需要讓類的用戶稍后定義函數。 顯然,您無法直接從構造函數運行它們。 如果您從構造函數運行它們,則需要事先對其進行定義。
說你的課有點像
function cls_something()
{
this.someFunctionThatIsRunLater = function() {
this.notify('hello');
}
}
然后你的客戶可以寫
var something = new cls_something();
something.notify = function(message)
{
console.log('The notification is ' + message);
}
然后,當客戶致電
something.someFunctionThatIsRunLater();
通知將被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.