-
[javascript] constructor functionjavascript 2022. 12. 1. 13:51
//생성자 함수 공부 //우리가 자주 사용하는 객체 리터럴 let obj = { name: 'hyun', age: 30 } //생성자 함수는 일반 함수와 동일하다. //new를 붙이지 않고 호출시 일반 함수로 동작함 //new를 붙이면 함수 내부적으로 주석에 해당하는 코드가 붙여져서 동작함 function Person() { // this = {}; this.name = 'hyun'; this.age = 30; // return this; } //테스트 - 생성자 함수에서 명시적으로 return할 경우 //명시적으로 리턴하지 않은 일반 케이스 function FuncNotReturn(){ } //객체가 아닌 것 리턴시 무시되고 내부적으로 만들어진 객체 리턴 function FuncReturnPrimitive() { this.testProperty = 'test property'; return 1; } //객체 리턴시 해당 객체로 대체되어 리턴 function FuncReturnObject() { this.testProperty = '하이'; return {testProperty: '헬로'}; } console.log(new FuncNotReturn()); console.log(new FuncReturnPrimitive()); console.log(new FuncReturnObject()); //테스트 - es6의 new.target function Constructor() { if (new.target) { console.log('new를 사용해 호출하였음'); } else { console.log('일반 함수처럼 호출하였음'); } } //let t = new Constructor(); //t= Constructor();
'javascript' 카테고리의 다른 글
[javascript] Promise then/catch/finally (0) 2023.10.01 [javascript] Object vs JSON (0) 2022.06.01 [javascript] jsp사용시 js template literal 해결 (0) 2022.05.02 [javascript] var,let,const/변수 scope/호이스팅 (0) 2022.05.01