Created
June 14, 2017 03:19
-
-
Save mrxf/1d41e1234e13f71ad49a499ea0488fcb to your computer and use it in GitHub Desktop.
ES问题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 定义一个函数,里面带有一个方法 | |
* 在不修改该方法的条件下,获取到o中所有的属性名 | |
*/ | |
var foo = (function(){ | |
var o = { | |
a: 1, | |
b: 2, | |
/**更多属性**/ | |
}; | |
return function(key) { | |
return o[key]; | |
} | |
})(); | |
/** 解决方案 */ | |
/** | |
* 声明一个symbol值,防止属性名重复 | |
*/ | |
var key = Symbol(); | |
/** | |
* 为Object提供一个原生值,调用该方法,返回this | |
* 这样o = new Object()就会拥有该方法,在调用的时候就会返回this值 | |
*/ | |
Object.defineProperty(Object.prototype, key, { | |
get() { | |
return this; | |
} | |
}); | |
var o = foo(key); | |
/** | |
* 使用getOwnPropertyNames方法获取所有的属性名 | |
* Object.keys()只能获取到可枚举的属性名 | |
*/ | |
console.log(Object.getOwnPropertyNames(o)); // ['a', 'b'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment