object - javascript - combining two constructors -
i'm trying extend 1 constructor another, using prototype:
var obja = function(name){ var obj = this; this.test.name = name; window.settimeout(function(){ console.log(obj.test.name) }, 1) } var objb = function(name){ this.name = 'test' } obja.prototype.test = new objb(); var = ['a', 'b', 'c', 'd'] for(var = 0; < a.length; i++){ new obja(a[i]) } this approach works great 1 object, if ( in example ) want create multiple, seems last entry ( 'd' ) overwrites previous, because in 4 cases obj.test.name returns d. maybe point out i'm doing wrong, or maybe other solution case. thanks.
javascript implements inheritance through chaining objects. obja has prototype property test instance of objb. shared instances of obja
obja.prototype.test = new objb(); now in constructor obja, modifies obja.prototype.test shared across instances of obja. means instances of obja have value of "d" since last iteration makes shared property hold "d".
if want hold unique name property each instance, you need attach instance, not shared parent.
var obja = function (name) { this.name = name; } now, seem notice there name on both instance, , shared parent. well, js reads instance first. if sees property name, takes it's value there. if not, reads shared parent, defaults 'test'.
it can seen here, made minor console.log on them. can see value has 2 name properties, 1 on instance, on on parent, reads instance's value first.
Comments
Post a Comment