2015-11-05 93 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>