Can't understand some fundamental things JavaScript, whether the circuit, whether the inheritance. There is a code of a small "class". Working example
https://jsfiddle.net/1ds0s3k9/.
Next, the code itself:
function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } function Notification( options ) { this.options = extend( {}, this.options ); extend( this.options, options ); this._init(); } Notification.prototype.options = { wrapper : document.body, message : 'yo!', type : 'error', elements : {} }; Notification.prototype._init = function() { var $this = this; this.html = document.createElement( 'div' ); this.html.innerHTML = ''+ this.options.message + '\\ some link\\ '; this.options.elements.link = this.html.querySelector('.ns-box-link'); this.options.elements.link.addEventListener('click', function() { console.log($this.options.elements.link); console.log($this); }); this.options.wrapper.append(this.html); }
Create a couple of instances
var ntfc1 = new Notification({ message: 'This is just a simple notice. Everything is in order and this is a simple link.', type: 'notice' }); var ntfc2 = new Notification({ message: 'Hello world', type: 'error' });
The problem occurs in the following code:
this.options.elements.link = this.html.querySelector('.ns-box-link'); this.options.elements.link.addEventListener('click', function() { console.log($this.options.elements.link); console.log($this); });
Why when you click the output
console.log($this);
displays a valid reference to each instance, and the output
console.log($this.options.elements.link);
references the element that is in the last instance of the class?
Video for clarity
https://youtu.be/kMUYs80tn7Y.