1

For whatever reason I'm getting TypeError: Object #<Num> has no method 'getNumber' when creating numberOne as an instance of Num

function Num(n) {
    var number = n;
    var getNumber = function() {
        return number;
    };
}

var numberOne = new Num(5);
console.log(numberOne.getNumber());

2 Answers 2

2

You're declaring getNumber as a local variable inside the function. Those do not become properties of constructed objects.

Use this:

  this.getNumber = function() { ...

In the constructor, this refers to the newly-created object to be initialized.

You can also use the prototype mechanism to provide object properties.

Sign up to request clarification or add additional context in comments.

Comments

1

You are creating a local variable called getNumber without attaching it to the object. Either give it to the object, or put it on the prototype:

this.getNumber = function() {

or

function Num(n) {
    this.number = n;
}

Num.prototype.getNumber = function() {
    return this.number;
}

If you are creating lots of objects, you probably want to put getNumber on the prototype so it doesn't get added to the object every single time one gets created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.