Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在prototype中的Javascript排序方法中访问外部“this”_Javascript - Fatal编程技术网

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

在prototype中的Javascript排序方法中访问外部“this”,javascript,Javascript,我有以下代码 var Index = function( columns ) { this.columns = columns; }; Index.prototype = { indexes: [], push: function( object ) { this.indexes.push(object); }, compare: function( object1, object2 ) { var compareVa

我有以下代码

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);
但是这个代码不起作用。compare函数没有看到索引原型的这一点,并表示它是未定义的。如何在prototype中访问外部排序功能


以下是。

简单/肮脏的解决方案:this.indexes.sorttthis.compare.bindthis;您始终可以执行ol'var self=this、绑定(如果目标浏览器支持)或将循环包装成闭包。@Sirko thanx。它成功了。你确定要在原型上建立索引吗?如果在末尾创建一个新的索引实例,您将看到该实例与testIndex共享索引数组。var i2=新指数;console.dirt2.index;有关prototype的更多信息,请点击此处: