简体   繁体   English

如何重写javascript方法并从类中调用?

[英]How to override javascript method and call from class?

Excuse the title but I'm not really sure what this is called (Maybe events?): 打扰一下标题,但我不确定这叫什么(也许是事件?):

I have created a class that someone will use: 我创建了一个班级,有人可以使用:

function cls_something()
{
    this.notify('hello');
}

Now the person using my class creates a method called 'notify' (as instructed by me) in order to listen for notifications and then perform their own custom code using the param I pass: 现在,使用我的课程的人创建了一个名为“ notify”的方法(按照我的指示),以便侦听通知,然后使用我通过的参数执行自己的自定义代码:

var something = new cls_something();

something.notify = function(message)
{
    console.log('The notification is ' + message);   
}

How do I call this method from within the class to give him the notification message? 如何在类中调用此方法以向他发送通知消息?

Fiddle 小提琴

I'm trying to achieve something like this... 我正在努力实现这样的目标...

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);
}

You can just call this.notify("Message"); 您可以只调用this.notify(“ Message”); You'd probably want to check to see if it's defined first, though. 不过,您可能需要检查是否首先定义了它。

EDIT 1: 编辑1:

Ok, so your problem here is that you're calling a function straight from the constructor, before it's defined. 好的,所以这里的问题是您在定义函数之前直接从构造函数中调用了函数。 If it needs to be defined in the constructor, then pass the function as a parameter. 如果需要在构造函数中定义它,则将该函数作为参数传递。

function cls_something(notifyFunction)
{
    notifyFunction('hello');
}

EDIT 2: 编辑2:

Just so we're clear, you can have the user of your class define functions later, if you'd like. 只是我们很清楚,您可以根据需要让类的用户稍后定义函数。 You just can't run them straight from the constructor, obviously. 显然,您无法直接从构造函数运行它们。 If you run them from the constructor, they need to be defined before hand. 如果您从构造函数运行它们,则需要事先对其进行定义。

Say your class was something like 说你的课有点像

function cls_something()
{
    this.someFunctionThatIsRunLater = function() {
        this.notify('hello');
    }
}

Then your client can write 然后你的客户可以写

var something = new cls_something();

something.notify = function(message)
{
    console.log('The notification is ' + message);   
}

Then, when the client calls 然后,当客户致电

something.someFunctionThatIsRunLater();

Notify will be called. 通知将被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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