简体   繁体   English

使用defineProperty的JS密钥重命名在Node.js中不起作用

[英]JS key rename with defineProperty won't work in Node.js

Object.prototype.prefixKeys = function (prefix) {
 for (var key in this) 
   this.hasOwnProperty(key) 
   && Object.defineProperty(this, prefix + key, {value: this[key]})
   && delete this[key]
}

Code above works as expected in chrome console. 上面的代码在chrome控制台中按预期工作。 But just removes keys in Node v6.10.2. 但只需删除Node v6.10.2中的密钥。 What am I doing wrong? 我究竟做错了什么?

The prefixed keys still exist on the object, but if you want them to show up when you, say console.log(obj) , then you need to make the properties enumerable : 对象上仍然存在带前缀的键,但如果您希望它们出现在您的console.log(obj) ,比如console.log(obj) ,那么您需要使属性enumerable

Object.prototype.prefixKeys = function (prefix) {
 for (var key in this) 
   this.hasOwnProperty(key) 
   && Object.defineProperty(this, prefix + key, {
     value: this[key],
     enumerable: true
   })
   && delete this[key]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM