如何在 javascript 中访问函数外部的数组

How to access array outside of a function in javascript

我只是想知道如何解决这个奇怪的 security/scope 问题:

function vector() {
    var array = [];
    return {
        append: function append(v) {
            array.push(v);
        },
        get: function get(i) {
            return array[i];
        },
        store: function store(i,v) {
            array[i] = v;
        }
    };
}

这是问的问题:

Can you spot any security concerns with this approach? Mainly, can we get access to the array outside of vector? Note*: the issue has nothing to do with prototypes and we can assume that global prototypes cannot be altered. Hint*: Think about using this in a method invocation. Can we override a method of vector?

例子

var v = vector();
v.append(1);
v.append(2);
var internalData = exploitVector(v); // [1, 2]

我的尝试+想法

很确定我应该按照提示所说以某种方式使用 this 关键字。 我是 javascript 的初学者,所以我不太了解 context。此代码是在文本编辑器 Atom 而非浏览器上编写的具有其他功能的文件中。

function exploitVector(v) {
    v.get = function() {
        return this.array;
    };
    console.log(v.get());
    return v.get();
}

此外,这只是我在 github 存储库上看到的一个有趣的练习。

Vector.store() 可以被滥用来修改数组方法(例如 array.push),然后是 v.append() 来触发修改后的 array.push 方法。例如,修改后的 push 方法可以执行类似 window.visiblearray=this 的操作,之后可以全局访问 visiblearray。

或者如下例所示,将this(数组实例)存储到局部范围的visiblearray,然后return它。

function vector() {
    var array = [];
    return {
        append: function append(v) {
            array.push(v);
        },
        get: function get(i) {
            return array[i];
        },
        store: function store(i,v) {
            array[i] = v;
        }
    };
}

var v = vector();
v.append(1);
v.append(2);
var internalData = exploitVector(v); // [1, 2]


function exploitVector(v) {
    var visible_array;
    v.store('push', function(x){visible_array=this}) // modify array push 
    v.append(12)                                     // trigger the modified array push
    console.log(visible_array);
    return visible_array
}