Primarily. Javascript does not support OOP class. OOP with it, inheritance is a prototype.
The following is an example of how to implement OOP prototype functions using your timer example:
function Timer(){ var time1 = null; var time2 = null; var timeLoop = null; } Timer.prototype.getTime = function(){ var day = new Date(); return day.getTime(); } Timer.prototype.start = function(){ time1 = this.getTime(); timeLoop = this.setInterval(function(){ time2 = this.getTime(); console.log(this.duration()); }.bind(this),500); } Timer.prototype.duration = function(){ return (time1 - time2) / 1000; }
See the section "Custom Objects" MDN Javscript Regeneration
There is nothing wrong with the way this is shown in your textbook. Itβs just a cleaner way, and the bind call is only needed for the console.log statement, which otherwise would associate this as window . If you get rid of it, you can also get rid of bind .
aa333 source share