class say {
constructor() {
}
sayHello() {
console.log('hello');
}
get sayGoodbye() {
console.log('goodbye');
}
static wocao() {
console.log('wocao');
}
}
这样一个class
定义的property都是不可遍历的
看了下babel转码到es5的代码
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
注意到descriptor.enumerable = descriptor.enumerable || false;
这句
想知道怎么设置 descriptor.enumerable
var say = function () {
function say() {
_classCallCheck(this, say);
}
_createClass(say, [{
key: 'sayHello',
value: function sayHello() {
console.log('hello');
}
}, {
key: 'sayGoodbye',
get: function get() {
console.log('goodbye');
}
}], [{
key: 'wocao',
value: function wocao() {
console.log('wocao');
}
}]);
return say;
}();
遍历ES6 Class的方法可以使用getOwnPropertyNames,它可以遍历非enumerable的成员:
class say {
constructor() {
}
sayHello() {
console.log('hello');
}
get sayGoodbye() {
console.log('goodbye');
}
static wocao() {
console.log('wocao');
}
}
Object.getOwnPropertyNames(say) // ["length", "name", "prototype", "wocao"] 获取静态的wocao
var x = new say
Object.getOwnPropertyNames(Object.getPrototypeOf(x)) // ["constructor", "sayHello", "sayGoodbye"]
你要是想改enumerable:
class say {
constructor() {
}
sayHello() {
console.log('hello');
}
get sayGoodbye() {
console.log('goodbye');
}
static wocao() {
console.log('wocao');
}
}
Object.defineProperties(say, {
"constructor": {
enumerable : true
},
"sayHello": {
enumerable : true
},
"sayGoodbye": {
enumerable : true
},
"wocao": {
enumerable : true
}
});
Object.keys(say) // ["wocao", "constructor", "sayHello", "sayGoodbye"]