function f() {
this.n = 'name';
this.onn = null;
if ( this.onn ) {
this.onn();
}
};
var of = new f();
of.onn = function() {
console.log( 1 );
};
var socket = new WebSocket( "example.com:8081" );
socket.onopen = function() {
console.log( 1 );
}
var MyWebSocket = function(url) {
this.url = url;
this.connection = this.connect(); // 2
Object.defineProperty(this, 'onopen', { // 4
set: function(cb) {
this.connection.then(cb.bind(this)); // 5
}
});
}
MyWebSocket.prototype.connect = function() {
console.log('connecting to %s', this.url);
return new Promise(function(resolve, reject) { // 3
setTimeout(resolve, 2000); // 6
});
}
var socket = new MyWebSocket('example.com:8081'); // 1
socket.onopen = function() {
console.log('connection to %s established', this.url); // 7
}
function f() {
this.n = 'name';
this.oncreate = function() {
console.log("oncreate");
};
this.create = function() {
/* your code */
this.oncreate();
};
};
var of = new f();
of.oncreate = function() {
console.log("Some message");
};
of.create();
function F(cb) {
this.n = 'name';
if(typeof cb === 'function') {
cb.call(this);
}
}
var of = new f(function() {
console.log(1);
});
He understands that the connection is true?
Find more questions by tags JavaScript
But it already the question does not apply directly - you can just cb to link to promis, if the context is not necessary (although usually retain it, of course). - aniya commented on July 9th 19 at 14:09
The result is completely different. Try experimenting with this option, there are clear differences - https://jsfiddle.net/koceg/p2utcp9j/1/ - aniya commented on July 9th 19 at 14:18