简体   繁体   中英

How to execute a constructor more than once without page refresh

I am new in using OOP methodology in javascript , I use the following code below as a constructor .

var post = function post() {}

I call the constructor inside a jQuery event handler

post = new post();

At first run or on each page refresh, it works well because a method invocation after calling the constructor gets executed. But on clicking the button that triggers the event the second time, it would not execute anymore, I instead get the following error message in firebug

TypeError: post is not a constructor

So why does it not work again after the first run, without a page refresh?

And how will I make it work continuously without page refresh?

So why does it not work again after the first run

Because you've overwritten the post symbol. This line:

post = new post();

Calls your post constructor and assigns the resulting object to the post variable. Now post isn't a constructor function anymore, it's the object created via new post .

Just use a different name:

var p = new post();

Side note: The overwhelming convention in JavaScript is that constructor functions start with an initial upper case letter, eg Post rather than post . You're free to ignore that convention, but it may make it difficult for others to read your code (for instance, here on SO).

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