javascript dynamic prototype
javascript
Solution
Apart from the obvious syntax error, the correct JavaScript way of inheritance is this:
// constructors are named uppercase by convention
function OtherObject(id1) {
this.id = id1;
};
OtherObject.prototype.test = function() {
alert(this.id);
};
function TestObject(id2) {
// call "super" constructor on this object:
OtherObject.call(this, id2);
};
// create a prototype object inheriting from the other one
TestObject.prototype = Object.create(OtherObject.prototype);
// if you want them to be equal (share all methods), you can simply use
TestObject.prototype = OtherObject.prototype;
var a = new TestObject("variable");
a.test(); // alerts "variable"
You will find lots of tutorials about this on the web.
Problem
I want extend a new JS object while creation with other object passing a parameter. This code does not work, because I only can extend object without dynamic parameter. ``` otherObject = function(id1){ this.id = id1; }; otherObject.prototype.test =function(){ alert(this.id); }; testObject = function(id2) { this.id=id2; }; testObject.prototype = new otherObject("id2");/* id2 should be testObject this.id */ var a = new testObject("variable"); a.test(); ``` Any suggestion?