tags:

views:

34

answers:

4

Hi,

I have a simple object in Javascript.

function myClass(x,y) {

this.x = x;

this.y = y;

}

and a prototype function

myClass.prototype.myfunction = function() {

console.log(this.x);

}

and in my main script,

var x = 2; var y = 4;

myinstance = new myClass(x,y);

myinstance.myfunction();

Instead of receiving x, I get undefined instead. Why is that?

+1  A: 

You are not using the new operator, myinstance is undefined.

var x = 2; var y = 4;

myinstance = new myClass(x,y);
myinstance.myfunction(); // will show `2` in the console

Edit: Since you say that you are using the new operator, I think you might be executing myinstance.myfunction(); at the console and you may be looking at the result (return value) of that method, which is actually undefined, because it doesn't contain a return statement.

See a working example here.

CMS
correction - I am using the new operator in my actual code. sorry for missing that out. still getting the same problem.
Pydroid
@Pydroid: Check my edit and the example I posted.
CMS
A: 

I think you should do myinstance = new myClass(x,y);

zed_0xff
+2  A: 

You forgot the new keyword:

myinstance = new myClass(x,y);

I tried the code, and with that addition it works.

Guffa
A: 
helle