samedi 17 décembre 2016

Extend an object with an extension in JS

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 http://ift.tt/1mXQHQw

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 );
  }
};

The for loop goes through the Subject's properties that I added before and then adds it to the Observer-object. How come it only adds those properties that I added before 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.

Aucun commentaire:

Enregistrer un commentaire