简体   繁体   中英

jQuery error - Uncaught TypeError: object is not a function

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM