I am writing a simple library that will read values from an object given a string property.
我正在编写一个简单的库,它将读取给定字符串属性的对象的值。
Is it possible to read the property but have a function execute without actually invoking the function?
是否可以读取属性,但在不实际调用函数的情况下执行函数?
something like:
喜欢的东西:
var obj = {
fn : (function malicious(){ deleteLotsOfFiles();
})()
}
if I do
如果我做
var foo = obj.fn;
is there a way just by reading the property to execute a (malicious) function?
是否有一种方法仅仅通过读取属性来执行(恶意的)函数?
3 个解决方案
#1
2
var obj = {
get fn() { deleteLotsOfFiles(); }
};
// later
var o = obj; // deleteLotsOfFiles has not been executed
console.log(o.fn); // you just deleted lots of files
#2
1
The malicious function would have already executed anyway before you even referenced it. Once the function is parsed by the engine, it is executed straight away (self-invoking).
恶意函数在您引用它之前就已经执行了。一旦该函数被引擎解析,它将立即执行(自调用)。
#3
1
An alternative
另一种选择
var o = Object.defineProperty(o, 'baz', {
get: function(){
console.log("Delete Everything!");
}
});
Then access o.baz
and they are deleted
然后访问啊。baz和它们被删除了
More Information on getters from MDN
更多来自MDN的信息。
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls.
有时,允许访问返回动态计算值的属性是可取的,或者您可能希望反映内部变量的状态,而不需要使用显式方法调用。
Seems pretty much like what you want to do.
看起来很像你想做的。
#1
2
var obj = {
get fn() { deleteLotsOfFiles(); }
};
// later
var o = obj; // deleteLotsOfFiles has not been executed
console.log(o.fn); // you just deleted lots of files
#2
1
The malicious function would have already executed anyway before you even referenced it. Once the function is parsed by the engine, it is executed straight away (self-invoking).
恶意函数在您引用它之前就已经执行了。一旦该函数被引擎解析,它将立即执行(自调用)。
#3
1
An alternative
另一种选择
var o = Object.defineProperty(o, 'baz', {
get: function(){
console.log("Delete Everything!");
}
});
Then access o.baz
and they are deleted
然后访问啊。baz和它们被删除了
More Information on getters from MDN
更多来自MDN的信息。
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls.
有时,允许访问返回动态计算值的属性是可取的,或者您可能希望反映内部变量的状态,而不需要使用显式方法调用。
Seems pretty much like what you want to do.
看起来很像你想做的。