Development/JavaScript
[JavaScript] Eval과 getOwnPropertyNames()
판교토끼
2020. 4. 15. 16:24
728x90
최근에 웹에서 함수명을 입력받아 실행하고, 그 return 값 object의 함수들을 출력할 일이 있었다.
Eval
string을 code로 실행하여 준다.
var objectName = "myObject.";
var methodName = "getProperty()";
var executeCode = objectName+methodName;
eval(executeCode); // myObject.getProperty()가 실행된다.
즉, input 태그로 함수명을 입력하면 해당 함수를 실행할 수 있다.
getOwnPropertyNames()
getOwnPropertyNames는 객체의 모든 속성(Property)의 이름을 반환한다. 즉, 배열이면 원소들을 반환하고 클래스는 멤버들을 반환한다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames에 있는 예제를 보면,
Object.getOwnPropertyNames()
The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
developer.mozilla.org
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// output: Array ["a", "b", "c"]
사용은 위와 같이 Object.getOwnPropertyNames()에 인자로 사용할 객체를 넣으면 된다.
728x90