You are assigning functions correctly (there is only one way of assigning functions), your problem is that the context of the function changes.
Consider this line:
this.ws.onopen = this.onOpen;
Possibility 1:
Now I assume, inside WebSocket, somewhere this function gets called as a response to an opening connection (like an event handler), probably like
this.onopen();
What this refers to inside a function is determined by how a function is called on run time (<- read this link, it helps a lot). It is not bound at definition time. In your case, this would refer to the WebSocket instance.
So inside if called this way, inside MyObject.prototype.onOpen, this refers to this.ws, the WebSocket instance, which does not have a ws property, and not the MyObject instance.
This can be solved in two ways:
Since this already refers to this.ws, you can call send directly on this:
MyObject.prototype.onOpen = function() {
this.send("hello");
};
If you want this inside MyObject.prototype.onOpen to always refer to the MyObject instance, you have to keep an explicit reference to the instance, e.g. through a closure:
var self = this;
this.ws.onopen = function() {
self.onOpen();
};
Now inside onOpen, this refers to the MyObject instance which has a property ws, just like you set it up in the constructor.
In browsers supporting ECMAScript 5, functions already have a method for this technique, called .bind():
this.ws.onopen = this.onOpen.bind(this);
Possibility 2:
It could also be that WebSocket calls onopen in such a way:
this.onopen.call(null);
In that case, this would either refer to window or would be undefined, depending on whether the code runs in strict mode or not (it does not matter, in any case it is a problem).
This situation could only be solved with the second solution from the first possibility.
Why does the first example work?
var ws = new WebSocket(something, somethingelse);
ws.onopen = function() {
ws.send("hello");
console.log("works");
}
In this case, the function you assign to ws.onopen is a closure, closing over the variables defined in this scope, also ws. In this sense it is similar to the second way of solving the problem, but
ws.onopen = function() {
this.send("hello");
console.log("works");
}
would probably work as well.
newkeyword? There's a bunch of stuff wrong here; what exactly are you trying to do?