我有以下javascript类
var a = function () {
this.data = {};
};
a.prototype.parseString = function (string) {
this.data = string.split(',');
}
a.prototype.performOperationB = function () {
this.iPo = _.map(this.data, function () {
if (item.indexOf('ip') > -1) {
return item;
}
});
}
a.prototype.save = function (string) {
this.parseString(string)
.performOperationB()
// some other chained methods
}
var b = new a();
b.save(string);
会返回TypeError: Cannot read property 'performOperationB' of undefined
是否可以在另一个方法中一个接一个地链接原型方法?
答案 0 :(得分:2)
从
返回this
a.prototype.parseString = function(string) {
this.data = string.split(',');
return this;
}
因为now方法返回undefined
var a = function () {
this.data = {};
};
a.prototype.parseString = function (string) {
this.data = string.split(',');
return this;
}
a.prototype.performOperationB = function () {
this.iPo = _.map(this.data, function (item) {
if (item.indexOf('ip') > -1) {
return item;
}
});
}
a.prototype.save = function (string) {
this.parseString(string)
.performOperationB()
}
var b = new a();
b.save('string');

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
&#13;