开发者

Why is my prototype function not returning the property of the instance?

开发者 https://www.devze.com 2023-01-03 15:23 出处:网络
I have a simple object in Javascript. function myClass(x,y) { this.x = x; this.y = y; } and a prototype function

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.开发者_JAVA百科 Why is that?


You forgot the new keyword:

myinstance = new myClass(x,y);

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


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.


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


hmm ... try to instanciate your function like this

var myClass = function (x,y) {

this.x = x;
this.y = y;
this.myfunction = function(){
    console.log(this.x);
}

}

this worked quite fine for me

0

精彩评论

暂无评论...
验证码 换一张
取 消