Why link closes on the last element of the instance?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
5 views
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.
by | 5 views

1 Answer

0 like 0 dislike
Because you have property elements in the prototype. All instances use the same object elements. In the end, how many instances you create, all will be one and the same object this.opions.elements with the property link overridden in the constructor the last instance.
Be careful with prototypes. In the prototypes the render only static, but not dynamic values, except that the counters, but it is very narrowly applicable and rare case.
by

Related questions

0 like 0 dislike
3 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
35,573 users