Node.js/JavaScript 内置类型的存根?
这个练习相当学术化,但它对于理解 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,但是是否可以对它们进行存根?
提前致谢。
This exercise is fairly academic, but it's useful in understanding JavaScript's behavior.
Why does this work:
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
and this doesn't:
var a = "hello world";
console.log(a.length); //'11'
a['length'] = 1000;
console.log(a.length); //still '11'... why??
I know it's possible to monkeypatch JavaScript built-in types such as String, but is it possible to stub them?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由 TJ Holowaychuk 提供:字符串是不可变的。所以看来以这种方式是不可能的。
Courtesy of TJ Holowaychuk: Strings are immutable. So it seems like it's not possible in this manner.