I am having an issues extending an object with another object in ECMA6. After I have extended the object in question it says it cannot find the method on the updated object. Here is my code:
Subject class:
// Subject to be observed
class Subject {
constructor() {
this.observers = new ObserverList();
}
addObserver(observer) {
this.observers.add(observer);
}
removeObserver(observer) {
this.observers.removeAt(this.observers.indexOf( observer, 0 ));
}
notify(context) {
for(let i = 0; i < this.observers.count(); i++) {
this.observers.get(i).update(context);
}
}
}
And my code where the object is extended:
/**
* Function to extend an object with another object
*/
function extend(obj, extension) {
Object.assign(obj, extension);
}
// Get our DOM elements
let controlCheckbox = document.getElementById("mainCheckbox"),
addBtn = document.getElementById("addNewObserver"),
container = document.getElementById("observersContainer");
// Concrete subject
// extend controlling checkbox with Subject class
extend(controlCheckbox, new Subject());
// Clicking the checkbox will trigger notifications to it's observers
controlCheckbox.onclick = () => {
controlCheckbox.notify(controlCheckbox.checked);
};
addBtn.onclick = addNewObserver;
function addNewObserver() {
let check = document.createElement('input');
check.type = 'checkbox';
extend(check, new Observer());
check.update = function(value) {
this.checked = value;
};
controlCheckbox.addObserver(check);
container.appendChild(check);
}
When the onclick is fired it is saying that the method controlCheckbox.addObserver is not defined. I have added a breakpoint to view the controlCheckbox object and I can see that method is available in the prototype. Should this not work? Can anyone point out where I am going wrong?
Object.assign()method only copies enumerable and own properties from a source object to a target object." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…extendskeyword to create the subclass.