1

I tried debugging but no luck as of yet! This Works:

function slider(direction){
this.direction = direction;
}

slider.prototype.move = function(){
console.log('moving');
};

var slider1 = new slider('backward');
console.log(slider1.direction);

var slider2 = new slider('forward');
console.log(slider2.direction);

This doesn't work:

var slider = new slider('backward');
console.log(slider.direction);

var slider2 = new slider('forward');
console.log(slider2.direction);

I know this would have something to do with the semicolon and I'd searched some other articles on this but couldn't find an answer to my problem

3
  • 1
    Is the slider function defined in the second block of code? Commented Oct 12, 2012 at 22:21
  • As lonesomeday suggests, this is likely a scope issue. If I was to guess, I'd bet that the first bit of code is hidden in a closure like $(document).ready(function(){/*closure*/}); Commented Oct 12, 2012 at 22:22
  • Yes. I just didn't want to copy the whole thing again. I am not sure why this error is happening.. tried debugging it in Chrome but doesn't give me any feedback? Commented Oct 12, 2012 at 22:23

2 Answers 2

2

It's hard to know the problem from your code but I think this line could cause it

var slider = new slider('backward');

You declared slider as function and as a variable at the same time. That is if my guess is right. This is because it is the only difference between the first code and the second

Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes, that's the problem. That's effectively saying new undefined('backward'). Good spot.
Hmm I see, but having this along works: var slider = new slider('backward'); console.log(slider.direction);
1

When you run

var slider = new slider('backward');
console.log(slider.direction);

you now have 2 variables called slider - one is a function and one is an instance of the object that function generates. When you ask the second slider to generate:

var slider2 = new slider('forward');
console.log(slider2.direction);

you're actually asking it to use the instance of the object as a variable... this feels really clunky to explain because they have the same names.

What you're doing in the second example, which causes it to fail, is the same as trying to do this in the first example:

var slider2 = new slider1('forward');
console.log(slider2.direction);

because the function name is the same as a variable containing an instance of it.

If this hasn't been explained massively clearly (which wouldn't surprise me) let me know and I'll try to make it make more sense.

1 Comment

Yes sir. I got it now! Thank you all for your help!

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.