这个练习是相当学术的,但它有助于理解 JavaScript 的行为。
为什么会这样:
var fs = require('fs');
console.log(fs.readdirSync('/').length); //approximately '28' on my Macbook
fs['readdirSync'] = function(){ return ['/tmp', '/bin']; };
console.log(fs.readdirSync('/').length); //'2' as expected
这不会:
var a = "hello world";
console.log(a.length); //'11'
a['length'] = 1000;
console.log(a.length); //still '11'... why??
我知道可以对 JavaScript 内置类型(例如 String)进行monkeypatch,但是可以对它们进行存根吗?
提前致谢。