2015-11-05 66 views
1

我有以下的JavaScript类方法链返回undefined

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

我认为你需要在这里进行过滤'this.iPo = _.map(this.data,函数(){'而不是'map' – Tushar

+0

@tushar还有我的映射函数的问题,但是并不是我寻找的解决方案。无论如何感谢队友。 – Bazinga777

回答

2

返回this

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

因为现在方法返回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>