thiswayup
thiswayup

Reputation: 2077

trying to understand javascript objects

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

Answers (3)

Matt Ball
Matt Ball

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

PointedEars
PointedEars

Reputation: 14980

  1. thiz = this aliasing is unnecessary here. You only need it for "private" properties by additional closures.
  2. thiz.nameOfMe is causing an additional closure here, needlessly.
  3. The value of 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.
  4. You are not using "the classical inheritance model". There are no classes. You are creating a 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.
  5. It is good code style to have constructor identifiers start with a capital letter: Person.

RTFM.

Upvotes: 1

JCOC611
JCOC611

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

Related Questions