2

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?

2
  • What is wrong with your code is the first version is just wrong (with no "return" in the getter), while the second version (which works) is written correctly. Also, I would argue it is impossible to write proper object oriented code in JavaScript. You can get close but never all the way, better just not to try. Commented Jul 8, 2013 at 11:05
  • 1
    get function return value .. you should use return keyword . this.getter = function(){return getData();} is the correct statement. Commented Jul 8, 2013 at 11:05

4 Answers 4

6

You need to use, because your getter method is nor returning any value to the caller.

In your getter, you are calling getData method which return the value of data but that value is not sent back the the caller of getter

this.getter = getData

or

this.getter = function () {return getData();}
Sign up to request clarification or add additional context in comments.

Comments

1

In the first sample of code you are not returning any value - just calling the function getData. The return value does not 'propagate' further (is not being passed further as return value for getter function.

// Here you are just calling getData
this.getter = function () {getData();} 

// Here you are returning the value returned by getData function
this.getter = function () {return getData();} 

Comments

0

The answer is there in your code only. You are not returning in the first case. How will you get it in alert if you don't return. Your second snippet fixes that.

Comments

0

You are not returning anything from first getter of sample. That's why you are getting undefined

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.