当我调用printData时,我在下面有一个类,但我得到this.collection是未定义的。
如何从printData()中的原型访问this.collection?还是我需要更改类结构。实际上,对象返回的函数是实习生按层次结构返回对象的函数。
提前致谢!
样本类别:
var DbProvider = (function () {
function DbProvider(db) {
var that = this; // create a reference to "this" object
that.collection = db;
}
DbProvider.prototype.create = function () {
return {
action: function () {
var y = {
printData: function () {
alert('Hello ' + this.collection.Name);
}
};
return y;
}
};
};
return DbProvider;
})();
用法:
var a = new DbProvider({ "Name": "John" });
a.create().action().printData();
您可以保存this
引用并将其绑定到printData
函数
var DbProvider = (function () {
function DbProvider(db) {
var that = this; // create a reference to "this" object
that.collection = db;
}
DbProvider.prototype.create = function () {
var self = this;
return {
action: function () {
var y = {
printData: function () {
alert('Hello ' + this.collection.Name);
}.bind(self)
};
return y;
}
};
};
return DbProvider;
})();
var a = new DbProvider({ "Name": "John" });
a.create().action().printData();
或者,您可以稍微重构一下,移到that
的外部范围DbProvider
并that
在其中使用printData
var DbProvider = (function () {
var that;
function DbProvider(db) {
that = this; // create a reference to "this" object
that.collection = db;
}
DbProvider.prototype.create = function () {
return {
action: function () {
var y = {
printData: function () {
alert('Hello ' + that.collection.Name);
}
};
return y;
}
};
};
return DbProvider;
})();
var a = new DbProvider({ "Name": "John" });
a.create().action().printData();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句