I get an error whenever I try to add the object BaseNet to IPv4Address.prototype. The error:
TypeError: Cannot read property 'ipInt' of undefined
just doesn't make sense. It's behaving like the getter is actually being executed when I copy the object to the prototype. Is there a way to copy this and not get an error like this?
var _s = require('underscore')
var BaseNet = {
get network(){
return new IPv4Address((this.ipInt & this.netmask.ipInt) >>> 0);
},
}
function IPv4Address (address){
this.ipInt = address
this.netmask = {}
this.netmask.ipInt = 255
}
_s.extend(IPv4Address.prototype,BaseNet)
//also fails with generic extend:
function extend(destination, source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
destination[k] = source[k];
}
}
return destination;
}
extend(IPv4Address.prototype,BaseNet)
First Edit
Maybe this is an answer to my own question. Resig had a post on this and this "modififed" extend method seems to do what I'm looking for. Can someone explain? It seems that it's a scoping problem, but i don't understand why it was behaving like someone was actually calling the getter during the extend operation.
http://ejohn.org/blog/javascript-getters-and-setters/
function extend(a,b) {
for ( var i in b ) {
var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);
if ( g || s ) {
if ( g )
a.__defineGetter__(i, g);
if ( s )
a.__defineSetter__(i, s);
} else
a[i] = b[i];
}
return a;
}
Second Edit
So I did some more experimenting and I came up with two other ways that seems to work. One uses the extend method posted earlier and another uses the defineProperties method form the ECMA spec pointed out in the comments. Is one better than the other? It seems that the "mixin" style works better for what i'm looking for, but the Object.create way also works.
var BaseNet = {}
Object.defineProperties(BaseNet, {
"network":{
enumerable:true,
get: function (){return new IPv4Address((this.ipInt & this.netmask.ipInt) >>> 0)}
}
});
function IPv4Address (address){
this.ipInt = address
this.netmask = {}
this.netmask.ipInt = 255
}
IPv4Address.prototype = Object.create(BaseNet)
var ip = new IPv4Address(12345)
ip.netmask
Alternatively, you can also do:
var BaseNet = {}
Object.defineProperties(BaseNet, {
"network":{
enumerable:true,
get: function (){return new IPv4Address((this.ipInt & this.netmask.ipInt) >>> 0)}
}
});
function IPv4Address (address){
this.ipInt = address
this.netmask = {}
this.netmask.ipInt = 255
}
extend(IPv4Address.prototype,BaseNet)
var ip = new IPv4Address(12345)
ip.netmask
IPv4Address's prototype is an empty object.ipIntis a a property of an instance ofIPv4Address, set when you call the constructor function.IPv4AddresstoBaseNet.... sorry.