简体   繁体   English

方法链返回未定义

[英]method chaining returning undefined

I have the following javascript class 我有以下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);

would return TypeError: Cannot read property 'performOperationB' of undefined 将返回TypeError: Cannot read property 'performOperationB' of undefined

Is it possible to chain the prototype methods one after another inside another method ? 是否可以在另一种方法内将原型方法一个接一个地链接?

Return this from 返回this

a.prototype.parseString = function(string) {
   this.data  = string.split(',');
   return this;
}

because now method returns undefined 因为现在方法返回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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM