【问题标题】:prototype can't passing property value even create new 'this'原型无法传递属性值,甚至创建新的“this”
【发布时间】: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


【解决方案1】:

问题在于您使用的是箭头函数。函数中的this是全局意义窗口的this。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多