这个丢失的范围不知道我如何使用apply/call


var DBProcessor = function(name){this.name=name;};
DBProcessor.prototype.CallBack = function(err, d){
if (err) {
    console.log("writeHosts. Error:", JSON.stringify(err, null, 2));
} else {
    console.log(".........");        
    console.log(this.name);  // >>>> UNDEFINED
    console.log(".........");
}
}
var DBP = new DBProcessor("Hosts");
function writeHosts(){
...
..         
db.batchWriteItem(param, DBP.CallBack);}

如何在DBP内获得变量"this"正在失去作用域,并且我无法影响DBP如何。CallBack被调用

var doc = require('dynamodb-doc');
var db = new doc.DynamoDB();

所以我不知道如何使用apply()或call()

如果你不能影响它的调用方式,你就不能把它作为原型函数。要么在构造函数中bind,要么将其定义为构造函数中的闭包,并使用旧的var _this = this;技巧来保持对正确this的引用。

嗯目前我有这个,它的工作如果有任何反对意见,让我现在谷歌"绑定"在同一时间

function DBProcessor(_this){
_this = this;
this.b = 1;
this.CallBack = function(err, d){
    if (err) {
        console.log("writeHosts. Error:", JSON.stringify(err, null, 2));
    } else {
        console.log(_this.a);
        console.log(_this.b); 
        console.log(".........");
    }
};
return this;}
var DBP = new DBProcessor();
DBP.a = 2;

这里有bind

function DBProcessor(){
return {
    a:1,
    _CallBack: function (err, d){
        if (err) {
            console.log("writeHosts. Error:", JSON.stringify(err, null, 2));
        } else {
            console.log(this.a);
            console.log(this.b);
            console.log(".........");
        }
    }
};
}
var DBP = new DBProcessor();
DBP.b = 2;
DBP.CallBack = DBP._CallBack.bind(DBP);

最新更新