簡體   English   中英

方法鏈返回未定義

[英]method chaining returning undefined

我有以下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

是否可以在另一種方法內將原型方法一個接一個地鏈接?

返回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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM