mardi 9 octobre 2018

Using prototype, TypeError: task1.completed is not a function

I follow a JS Design pattern tutorial which explain using prototype to prevent we new 'this' every time when we new an object. However, when I run the code as below, it pop up the error as below. I followed the tutorial code completely, that's why I don't understand why on the tutorial it has no error show up.

TypeError: task1.completed is not a function

    var Task = function (name) {
        this.name = name;
        this.completed = false;

    }

    Task.prototype.completed = function () {
        console.log('completing task: ' + this.name);
        this.completed = true;
    }


    Task.prototype.save = function () {
        console.log('saving task: ' + this.name);
    }

    var task1 = new Task('create a demo for constructors');
    var task2 = new Task('create a demo for modules');
    var task3 = new Task('create a demo for singletons');
    var task4 = new Task('create a demo for prototypes');

    task1.completed();
    task2.save();
    task3.save();
    task4.save();

My another question is, as the tutorial mentioned, we should always use this way to implement class, but why I haven't seen this pattern in many code? I only see the usage of prototype in implementing JS built in methonds, eg. Object.prototype.toString(). But in our real life, I haven't seen it a lot. Is just I'm not familiar JS code?

Aucun commentaire:

Enregistrer un commentaire