I follow a tutorial to using prototype to define methods of object. However, I still can't passing the property by using either this or
var _this = this;
The idea is, in main.js, it create 4 variables which all instantiate Task object. In the task.js is where my task object defined, it use prototype to create two method, complete and save, in each of them try to print out this._name property of Task object.
Before I read people mentioned the 'this' issue, so I tried to use
var _this = this
so in the
prototype.complete()
should have a new 'this', am I correct?
However the output is below, I still get undefined.
Getting task 1
completing task: undefined
saving task: undefined
saving task: undefined
saving task: undefined
Below is my code
my script.js code
var Task = function (data) {
this._name = data.name;
this._completed = data.completed;
};
Task.prototype.complete = () => {
var _this= this;
console.log('completing task: ' + _this._name);
this._completed = true;
};
Task.prototype.save = () => {
var _this= this;
console.log('saving task: ' + _this._name);
};
module.exports = Task;
my main.js
var Task = require('./task');
var Repo = require('./taskRepo');
var task1 = new Task(Repo.get(1));
var task2 = new Task({name: 'create a demo for modules'});
var task3 = new Task({name:'create a demo for singletons'});
var task4 = new Task({name:'create a demo for prototypes'});
task1.complete();
task2.save();
task3.save();
task4.save();
my taskRepo.js
var repo = function () {
return {
get: function (id) {
console.log('Getting task ' + id);
return {
_name:'new task from db'
};
},
save: function(task){
console.log('Saving'+ task._name+'to the db');
}
};
};
module.exports = repo();
The problem is that you are using an arrow function. The this in the function is the this of global meaning window.