Reputation: 2077
I've written this piece of code to try help me understand how objects work in js a bit more.
function person(personName){
var thiz = this;
var nameOfMe = (typeof(personName) === 'undefined')? 'default':personName;
var faveFood = 'stuff';
thiz.speakName =function(){
alert('I am '+ thiz.nameOfMe);
}
thiz.gotFoodAlert = function(){
alert('Yummy! I haz ' + thiz.faveFood )
}
}
var someGuy = new person('joe');
someGuy.faveFood = 'cheesecake';
someGuy.speakName();
var elseGuy = new person();
elseGuy.nameOfMe = 'bob';
elseGuy.speakName();
I'm trying to simulate a classical inheritance model to build a class then instantiate a person. Setting it separately in elseGuy.speakName() alerts 'bob' ok.
What I don't understand is why doesnt the someGuy.speakName() alert 'joe' when I instantiate?
update: on further reflection and taking notes from people commented, I should just give up trying to simulate a classical inheritance model.
Upvotes: -1
Views: 319
Reputation: 360046
Because nameOfMe
is not a property of this
in the first example. Try the following instead:
function person(personName) {
var nameOfMe = (typeof personName === 'undefined')? 'default':personName;
var faveFood = 'stuff';
this.speakName = function () {
alert('I am ' + nameOfMe);
}
this.gotFoodAlert = function () {
alert('Yummy! I haz ' + faveFood )
}
}
Even better:
function Person(personName) {
this.nameOfMe = personName ? 'default' : personName;
this.faveFood = 'stuff';
}
Person.prototype.speakName = function () {
alert(this.nameOfMe);
};
Person.prototype.gotFoodAlert = function () {
alert('Yummy! I haz ' + this.faveFood);
};
Upvotes: 2
Reputation: 14980
thiz = this
aliasing is unnecessary here. You only need it for "private" properties by additional closures.thiz.nameOfMe
is causing an additional closure here, needlessly.thiz.nameOfMe
is not "joe"
because the object referred to by thiz
does not have a nameOfMe
property yet. The nameOfMe
variable in constructor code is something else.person
instance, that is, an object that has person
as its constructor, and the object that person.prototype
currently refers to next in its prototype chain. Nothing more, nothing less.Person
.RTFM.
Upvotes: 1
Reputation: 19759
You have to set nameOfMe
as a property of thiz
:
thiz.nameOfMe = (typeof(personName) === 'undefined')? 'default':personName;
Also, unless you absolutely have to, why don't you use the normal this
instead of thiz
?
Upvotes: 1