BernaMariano
BernaMariano

Reputation: 866

OOP Javascript - Accessing a privileged method from public method via another public method

var Person = function (name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.scream = function () {
    this.WhatToScream.screamAge();
}

Person.prototype.WhatToScream = function () {
    this.screamAge = function () {
        alert('I AM ' + this.age + ' YEARS OLD!!!');
    }
    this.screamName = function () {
        alert('MY NAME IS ' + this.name + '!!!')
    }
}

var man = new Person('Berna', 21);
man.scream();


// This code raises:
// Uncaught TypeError: Object WhatToScream has no method 'screamAge'

Upvotes: 0

Views: 78

Answers (2)

ThomasH
ThomasH

Reputation: 23536

Here's a re-definiton that is closer to your original code:

Person.prototype.scream = function () {
  new this.WhatToScream().screamAge();
}

Upvotes: 2

c69
c69

Reputation: 21517

var Person = function (name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.scream = function () {
    // get function screamAge from container WhatToScream,
    // which is available in the instance of the object,
    // because it was defined in the prototype
    // and then call it with thisArg being current this,
    // which is pointing to current container,
    // * which at runtime is man
    this.WhatToScream.screamAge.call(this);
}

Person.prototype.WhatToScream = {
    screamAge: function () {
        alert('I AM ' + this.age + ' YEARS OLD!!!');
    },
    screamName: function () {
        alert('MY NAME IS ' + this.name + '!!!')
    }
}

var man = new Person('Berna', 21);
man.scream();

If you want to keep WhatToScream as a function, you will need to call it to use the object it returns:

Person.prototype.scream = function () {
    this.WhatToScream().screamAge.call(this);
}

Person.prototype.WhatToScream = function () {
    return {
        screamAge: function () { ... }, 
        screamName: function () { ... },
    }
}

Upvotes: 1

Related Questions