Grant Herman
Grant Herman

Reputation: 973

Javascript Prototype Error

I have been trying to create my own Javascript function, and then add methods using Prototype

So I create a function:

function createObject(){
    this.value = 0;
}

And then I create the Prototype Method:

createObject.prototype.once = function(){
       return this.value+1
};

Then I create the instance of the object:

var x = createObject();

Then, when I try to run x.once() I get:

Uncaught TypeError: Cannot read property 'once' of undefined
at <anonymous>:1:2

And I have no idea why.

Upvotes: 0

Views: 489

Answers (3)

user663031
user663031

Reputation:

You could find this error by placing a breakpoint on the this.value = 0; line, and examining this; you will find that it is not what you expect.

The most robust solution is to rewrite your constructor to make sure it's being called with new, using new.target:

function CreateObject() {
  if (!new.target) throw new TypeError('CreateObject() must be called with new');

  this.value = 0;
}

const object = CreateObject();

Linters can help you find this type of error as well. For example, eslint has the new-cap option. It will complain if you call a non-capitalized function with new, or call a capitalized function without new. To take advantage of this, you'll have to follow the convention of capitalizing constructors, as in CreateObject.

TypeScript (or ES6 as well) would report an error if you used class and tried to instantiate it without new:

class CreateObject {
  value = 0;

  once() { return this.value = 0; }
}

var x = CreateObject();

Value of type 'typeof CreateObject' is not callable. Did you mean to include 'new'?

Upvotes: 2

Emran
Emran

Reputation: 188

When you make instance of class, you have to use new keyword, before class name.

var x = new createObject();

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

For more information MDN

Upvotes: 1

Joshua Kleveter
Joshua Kleveter

Reputation: 1769

You'll need to use var x = new createObject().

In short, the new keyword is what sets up the prototype chain and this bindings within the object that your function returns to x.

I'd recommend that you take a look at the MDN page for more details.

Upvotes: 1

Related Questions