在原型的Javascript排序方法中访问外部“this”

时间:2014-11-05 10:02:25

标签: javascript

我有以下代码

var Index = function( columns ) {
    this.columns = columns;
};

Index.prototype = {
    indexes: [],

    push: function( object ) {
        this.indexes.push(object);
    },

    compare: function( object1, object2 ) {
        var compareVal = -1;
        for( var i = 0; i < this.columns.length ; i++ ) {
            compareVal = object1[this.columns[i]].localeCompare(object2[this.columns[i]]);
            if( compareVal != 0 )
                return compareVal;
        }
        return compareVal;
    },

    rebuildIndexes : function() {
        this.indexes.sort(this.compare);
    },
};

var testIndex = new Index( [ 'type', 'name', 'id' ] );
testIndex.push({ "id": "123", "name": "Name 1", "type": "4" } );
testIndex.push({ "id": "34", "name": "Name 3", "type": "3" }  );
testIndex.push({ "id": "13", "name": "Name 2", "type": "2" }  );
testIndex.push({ "id": "73", "name": "Name 4", "type": "2" }  );
testIndex.rebuildIndexes();
var text = "";
for(var i=0; i<testIndex.indexes.length;i++) {
    text += testIndex.indexes[i]['type'] + ", ";
}
$('body').html(text);

但是这段代码不起作用。比较函数没有看到Index原型的 this ,并且说它未定义。如何在原型中的sort函数中访问外部。

这是JSFiddle Link

0 个答案:

没有答案