How do you extend an object prototype with a nested namespace?
http://jsfiddle.net/2t5314nu/2/
I want to be able to call nested methods from Obj.prototype
like this.nested.method
and be able to access prototype properties and methods from nested
as this.prop
.
However, when I use jQuery $.extend
, the init
method from nested
overrides the one from Obj.prototype
. In fact, Obj.prototype.init
is never called.
I want to avoid overriding Obj.prototype.init
with nested.init
. I would be fine with using something other than $.extend
.
function Obj() {
this.prop = 'val';
this.init();
}
Obj.prototype = {
init: function() {
console.log('object init');
console.log('prop in object init: ' + this.prop);
$('#object-init').text('object init');
this.nested.init();
this.nested.method();
}
};
var nested = {
init: function() {
console.log('nested init');
console.log('prop in nested init: ' + this.prop);
$('#nested-init').text('nested init');
},
method: function() {
console.log('nested method');
console.log('prop in nested method: ' + this.prop);
$('#nested-method').text('nested method');
}
};
$.extend(true, Obj.prototype, nested);
new Obj();