I am new to object oriented programming in JavaScript. I'm not sure what's wrong with following program:
function Sample() {
var data = "one";
var getData = function () {
return data;
};
this.getter = function () {
getData();
};
}
var s = new Sample;
alert(s.getter()); // alerts undefined
The above program doesn't work as I expected it to, but the following program does:
function sample() {
var data = "one";
var getData = function () {
return data;
};
this.getter = function () {
return getData();
};
}
var s = new Sample;
alert(s.getter()); // alerts "one"
Why is it so?
returnkeyword .this.getter = function(){return getData();}is the correct statement.