Reputation: 22490
Created an object Blubb which has to do some things. There are several of those objects. Now there is another object BlubbWatcher which when it has to it has to reset some things from Blubb.
I've tried to create prototype.functions
and thought then I can use them later using Object.create(Blubb)
. Now I can use the functions but the properties are empty/undefined cause I guess I don't have the right instance of Blubb in BlubbWatcher
Simplified example to demonstrate my problem:
var Blubb = function(element) {
this.element = element;
this.header = 'hello world';
this.init();
};
Blubb.prototype.init = function() {
console.log(this.header);
};
////////////////
var BlubbWatcher = function(sections){
this.sections = sections;
this.Blubb = Object.create(Blubb);
Array.prototype.forEach.call(
this.sections,
(function (element) {
// call Blubb.init from here makes header undefined
console.log(' - next log is undefined - ')
this.Blubb.prototype.init(element);
}).bind(this)
);
};
//////////////////
var sections = document.querySelectorAll('section');
Array.prototype.forEach.call(
sections,
function (element, index) {
new Blubb(element);
}
);
new BlubbWatcher(sections);
<section>section</section>
How can I use the functions and properties from Blubb in BlubbWatcher?
Upvotes: 0
Views: 43
Reputation: 3090
var Blubb = function(element, header) {
this.element = element;
this.header = header;
this.init();
};
Blubb.prototype.init = function() {
console.log(this.header, 'header');
};
////////////////
var BlubbWatcher = function(blubbs){
this.blubbs = blubbs;
Array.prototype.forEach.call(
this.blubbs,
function (element) {
console.log(' - next log is NOT undefined :) - ')
element.init();
}
);
};
//////////////////
var sections = document.querySelectorAll('section');
var blubbs = Array.prototype.map.call(
sections,
function (element) {
return new Blubb(
element,
document.querySelector('header')
);
}
);
new BlubbWatcher(blubbs);
I have rewritten your code. What happen is that you are actually creating new instances of Blubb in your BlubbWatcher instead of using the previous instances created.
In order to make it work, I have used .map
on sections and got an array containing the instances of Blubb, then I've added these instances to the BlubbWatcher.
If you are in a browser and must support old browsers, consider using lodash
library with _.map
.
Upvotes: 1