5 ms·
This article is wrong. You need to use prototype when defining your functions. Here is how to do it: <html> <head> <script> function HotDog () { thi
by volida 17y ago
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>
- Bluem00 17y agoWhile you can use prototype, why do you need to? What specifically do you mean by "the article is wrong?"
- volida 17y agoif 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.
- DougBTX 17y agoTry 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.
- deleted 17y ago[deleted]
- volida 17y agoSorry, I was typing a bit fast. This should be ok. window.onload= function() { setTimeout( "myHotDog.getCondiments();", 3000); };
- jmtulloss 17y agoI 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.
- deleted 17y ago[deleted]
- volida 17y agoSorry, I wasn't clear enough. I didn't mean what you are explaining is wrong.