typeof, instanceof, Object.prototype์ ์ฐจ์ด์ ์ ์์๋ณด๊ธฐ ์ ์
JS์ ํ์ ๋ค์ ๊ฐ๋จํ ์ดํด๋ณด์!
JS ํ์
PRIMITIVE(์์๊ฐ) vs REFERENCE(์๋ฃํ ๊ฐ์ฒด)
PRIMITIVE(์์๊ฐ) | REFERENCE(์๋ฃํ ๊ฐ์ฒด) |
string, boolean, number.. | Array, function, Date, String... |
๊ทธ๋ ๋ค๋ฉด ํ์ ๊ฒ์ฌํ ๋ 'typeof'๋ก ๋ชจ๋ ๊ฒ์ ๊ตฌ๋ณํ ์ ์์๊น? NO!
REFERENCE(์๋ฃํ ๊ฐ์ฒด)๋ 'typeof'๋ก ๊ฐ๋ณํด๋ด๊ธฐ ์ด๋ ต๋ค.
์๋๋ฉด, JS๋ ๋์ ์ผ๋ก ๋ณํ๋ ์ธ์ด๋ก, ํ์ ๋ ๋์ ์ผ๋ก ๋ณํํ๊ธฐ๋๋ฌธ์ด๋ค.
// ์ด๋ฒ ์ฝ๋์์ console.log()๋ฅผ ์๋ตํ๋ค.
function a(){}
class b{}
typeof a //function
typeof b //function -> b๋ class๊ฐ ์ ๋ต์. ์๋ชป ๊ฐ๋ณํจ.
๋ํ 'typeof'๋ Wrapper๊ฐ์ฒด๋ ๊ฐ๋ณํ์ง ๋ชปํ๋ค.
const str = new String('๋จ')
typeof str //object -> str์ String์. ์๋ชป ๊ฐ๋ณํจ.
๋๋ถ์ด js์์ ์ธ์ ํ๋ ์ธ์ด์ ์ธ ์ค๋ฅ๊ฐ ์กด์ฌํ๋ค.
๋ฐ๋ก ๊ทธ๊ฑด << 'typeof'์์ null์ object๋ก ์ธ์ํ๋ ๊ฒ >>
console.log(typeof null) // object
๊ทธ๋ ๋ค๋ฉด 'instanceof'๋ ์ด๋จ๊น?
'instanceof': ๊ฐ์ฒด์ ํ๋กํ ํ์ ์ฒด์ธ์ ๊ฒ์ฌํ๋ค. (์ฆ Parent๋ฅผ ๊ฒ์ฌํ๋ค๊ณ ์ดํดํ๋ฉด ๋๊ฒ ๋ค.)
unction Pet(name,age){
this.name=name;
this.age=age;
}
const cat=new Pet('๋ฃจํค',2)
const c={
name:'test',
age:1
}
cat instanceof Pet //true
c instanceof Pet //false
์์ ์์ ๋ฅผ ๋ณด๋ฉด instanceof๋ก REFERENCE ๊ฐ์ฒด๋ฅผ ์ ๋๋ก ๊ฐ๋ณํ๋ ๊ฒ ๊ฐ์ง๋ง,
ํจ์ ์ด ์๋ค!
<< ๋ชจ๋ REFERENCE์ Parent๋ Object>> ๋ผ๋ ์ ์ด๋ค.
const arr=[]
const func=function(){}
const date=new Date()
arr instanceof Array //true
func instanceof Function //true
date instanceof Date //true
// ์ต์์๋ Object๊ฐ ์๊ธฐ๋๋ฌธ์ type์ ๊ตฌ๋ณํ๋๋ฐ ์ด๋ ค์์ด ์์
arr instanceof Object //true
func instanceof Object //true
date instanceof Object //true
์ฐ๋ฆฌ๊ฐ REFERNCE๋ฅผ ๊ฐ๋ณํด๋ด๊ธฐ ์ํ ํด๊ฒฐ๋ฐฉ๋ฒ์!
Object๊ฐ ๋ชจ๋ ๊ฐ์ฒด์ ์ต์์ ๊ฐ์ฒด์์ ํ์ฉํด์ Object.prototype์ ์ด์ฉํด์ ๊ฐ๋ณํ๋ ๊ฒ์ด๋ค.
Object.prototype.toString.call(arr) // object Array
Object.prototype.toString.call(func) // object Function
Object.prototype.toString.call(date)) // object Date
'javascript > ํด๋ฆฐ์ฝ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] ํด๋ฆฐ์ฝ๋ - ๊ฒฝ๊ณ ๋ค๋ฃจ๊ธฐ (min~max, first~last, prefix-suffix) (0) | 2022.03.29 |
---|---|
[JS] ํด๋ฆฐ์ฝ๋ - eqeq ์ค์ด๊ธฐ, ํ๋ณํ ์ฃผ์ํ๊ธฐ, isNaN (0) | 2022.03.24 |
[JS] ํด๋ฆฐ์ฝ๋ (undefined, null) ๊ฐ๋ , ์ฐจ์ด์ (0) | 2022.03.22 |
[JS] ํด๋ฆฐ์ฝ๋ - ๋ณ์ (0) | 2022.03.15 |