【发布时间】:2018-10-10 15:03:46
【问题描述】:
我按照教程使用原型来定义对象的方法。但是,我仍然无法使用 this 或
传递属性var _this = this;
这个想法是,在 main.js 中,它创建了 4 个变量来实例化 Task 对象。在 task.js 中是我的任务对象定义的地方,它使用原型创建两个方法,完成和保存,在每个方法中都尝试打印出任务对象的 this._name 属性。
在我读到人们提到'this'问题之前,我尝试使用
var _this = this
所以在
prototype.complete()
应该有一个新的“this”,对吗?
但是输出如下,我仍然不确定。
获取任务 1
完成任务:未定义
保存任务:未定义
保存任务:未定义
保存任务:未定义
下面是我的代码
我的 script.js 代码
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;
我的 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();
我的 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();
【问题讨论】:
标签: javascript node.js scope this prototype