Can someone explain to me what is happening here?
function extend( obj, extension ){
for ( var key in extension ){
obj[key] = extension[key];
}
}
Context: Used in the Observer Pattern https://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript
For example:
// Extend the controlling checkbox with the Subject class
extend( controlCheckbox, new Subject() );
With
function Subject(){
this.observers = new ObserverList();
}
Subject.prototype.addObserver = function( observer ){
this.observers.add( observer );
};
Subject.prototype.removeObserver = function( observer ){
this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};
Subject.prototype.notify = function( context ){
var observerCount = this.observers.count();
for(var i=0; i < observerCount; i++){
this.observers.get(i).update( context );
}
};
What I think is going on: The for loop goes through the Subject
's properties that I added before and then adds it to the Observer-object.
What I don't understand: How come it only adds those properties that I added before (i.e. observers, addObserver, removeObserver, notify) but not ALL properties of the extension object?
For example when I print out the extension object I can see that the constructor
- or the __proto__
property is NOT added.