Hacker News new | past | comments | ask | show | jobs | submit login

This article is wrong. You need to use prototype when defining your functions.

Here is how to do it:

  <html>
  <head>
  <script>

  function HotDog () {
	this.name=arguments[0];
  } 

  HotDog.prototype.name=null;

  HotDog.prototype.getCondiments= function () { 
	document.getElementById('test').innerHTML='started...'  +this.name;
  };
  var myHotDog = new HotDog('test 001');

  window.onload= function() {
	setTimeout(30, myHotDog.getCondiments());
  };

  </script>

  </head>
  <body>
  <div id=test>loading...</div>
  </body>
  </html>



While you can use prototype, why do you need to? What specifically do you mean by "the article is wrong?"


if you dont use prototype the function will not belong το the new object you create, therefore you will not be able το call the function from settimeout, which was the problem the author assumed το have.


Try extending the time on your timeout in the example, say to 30000 milliseconds. You might get a surprise when you see your function get called immediatley.

In the article, you are right that he should use prototype, but not for the reason you mention. In the example, he does this.foo = function, so the function does get associated with the object. The problem is that the function gets recreated every time the HotDog constrictor gets called. Better to put getCondiments on the prototype, so that it is only defined once.


Sorry, I was typing a bit fast. This should be ok.

  window.onload= function() {  
	setTimeout( "myHotDog.getCondiments();", 3000);
  };


I would never not use a prototype in production code, but prototypes are a different topic that I wanted to avoid for this article. I'm just trying to explain "this".

Also, your code isn't right. You're calling myHotDog.getCondiments instead of passing a reference to setTimeout.


Sorry, I wasn't clear enough. I didn't mean what you are explaining is wrong.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: