Reputation: 59365
I know this is simple and it's probably out there some where I'm just not sure what to look for "class inheritance"? I'm trying to access ship's this
function from within cargo. Ideas?
var Ship = function() {
this.id = Math.floor(Math.random() * 1000000);
};
var Cargo = function(){
this.id = Math.floor(Math.random() * 1000000);
}
Cargo.prototype.push = function(string){
return string;
}
Ship.prototype.cargo = Cargo;
module.exports = Ship;
Upvotes: 0
Views: 79
Reputation: 4693
The function of the prototype can already access this
of an instance.
var Ship=function () {
this.id=Math.floor(Math.random()*1000000);
};
var Cargo=function () {
this.id=Math.floor(Math.random()*1000000);
};
Cargo.prototype.push=function (string) {
return string;
};
Ship.prototype.cargo=function () {
var cargo=new Cargo();
cargo.ship=this;
return cargo;
};
var ship1=new Ship();
var cargo1=ship1.cargo();
var cargo2=ship1.cargo();
alert(cargo1.ship.id===cargo2.ship.id);
var ship2=new Ship();
var cargo3=ship2.cargo();
var cargo4=ship2.cargo();
alert(cargo3.ship.id===cargo4.ship.id);
alert(cargo1.ship.id===cargo3.ship.id);
Upvotes: 1
Reputation: 14671
You could extend the object either using underscore or mimic its source:
http://underscorejs.org/#extend
http://underscorejs.org/docs/underscore.html#section-78
Edit: i think what you want is this.
var Cargo, Ship, cargo;
Ship = (function() {
function Ship() {}
return Ship;
})();
Cargo = (function() {
function Cargo(ship) {
this.ship = ship;
}
return Cargo;
})();
cargo = new Cargo(new Ship());
alert(cargo.ship);
Upvotes: 1