There is no way for the errors
object to know its "parent" directly. It's a different object, and technically you could grab a reference to it and make it a property of some other object.
There are a few ways to approach a solution.
You could move the declaration of errors
into the constructor function and use a closure to keep a reference to the parent. This way errors
is still a distinct object that you can reference. You just can't use prototype
because you need the closure scope.
var constructor = function(name, type) {
var errorParent = this;
this.name = name;
this.type = type;
this.errors = {
message: function() {
return "error";
},
presence: function() {
// access the parent's each() method
errorParent.each(function() {
console.log('iteration');
});
}
},
};
A second alternative would be to make the message
and presence
methods become members of the constructor's prototype. Now you can keep the prototype
structure, but there is no errors
object.
constructor.prototype: {
init: function() {
console.log(this.name);
console.log(this.type);
},
errors_message: function() {
return "error";
},
errors_presence: function() {
this.each(function() {
console.log('iteration');
});
},
each: function(cb) {
this.type.forEach(function(t) {
cb();
});
};
};
A third alternative is to make Errors
an entirely separate class and create an instance errors
within your constructor. Then the errors
object would have an explicit reference to the object it is responsible for managing.
var constructor = function(name, type) {
this.name = name;
this.type = type;
this.errors = new Errors(this);
};
...and elsewhere in the code...
function Errors(object) {
this.object = object;
};
Errors.prototype.message = function() {
return "error";
};
Errors.prototype.presence = function() {
this.object.each(function() {
console.log('iteration');
};
};
The third approach seems the cleanest to me, but you'll have to decide which approach fits your application best.
P.S. As an aside, I know JavaScript object literals are all the rage for declaring entire classes, but many times (as in this case) using them actually restricts the way developers think about the code instead of enlightening them. IMHO.