1

my question is probably identical and have same motive as this here i ain't using jQuery. I would like a javascript solution.

my object looks like below:

function Person(name, age, weight) {
    this._name = name;
    this._weight = weight;
    this._age = age;
    this.Anatomy = {
        Weight: this._weight,
        Height: function () {
            //calculate height from age and weight
            return this._age * this._weight;

//yeah this is stupid calculation but just a demonstration
//not to be intended and here this return the Anatomy object
//but i was expecting Person Object. Could someone correct the 
//code. btw i don't like creating instance and referencing it 
//globally like in the linked post
                    }
                }
            }
Community
  • 1
  • 1
Deeptechtons
  • 10,945
  • 27
  • 96
  • 178

1 Answers1

3
this.Anatomy = {
          //'this' here will point to Person
    this.f = function() {
         // 'this' here will point to Anatomy.
    } 
}

Inside functions this generally points at the next thing up a level. The most consistent way to solve this would be

this.Anatomy = {
    _person: this,
    Weight: this._weight,
    Height: function () {
        //calculate height from age and weight
        return _person._age * _person._weight;
    }
}

Alternatively you can do this

function Person(name, age, weight) {
    this.Anatomy = {
        weight: weight,
        height: function() { return age*weight; }
    };
}
Raynos
  • 166,823
  • 56
  • 351
  • 396
  • thanks for that neat tip but creating a private variable that references Person object is this my only way out?? can't i do anything else to solve the problem – Deeptechtons May 27 '11 at 08:08
  • @Deeptechtons you can also just use the arguments which are in scope directly. – Raynos May 27 '11 at 08:38