Object

Object API ์‚ฌ์šฉ๋ฒ•

prototype์˜ ์œ ๋ฌด์˜ ์ฐจ์ด์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด์ž.

//Object.keys()
var arr = ["a","b","c"];
//๋ฐฐ์—ด์—์„œ key๋Š” index์ด๋ฏ€๋กœ ๋ฐฐ์—ด์˜ index๋ฅผ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ดํ•œ๋‹ค.
console.log('Object.keys(arr)', Object.keys(arr));//will alert "0,1,2"

//Object.prototype.toString()
var o = new Object();//๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์—ฌ o์— ํ• ๋‹นํ•œ๋‹ค.>Object๋Š” ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ผ๋Š” ๊ฒƒ์ด๋‹ค.
console.log('o.toString()', o.toString());

var a = new Array(1,2,3);
console.log('a.toString()', a.toString());

Object ํ™•์žฅ

์–ด๋Š ๊ฐ์ฒด์—์„œ๋‚˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์ž.

containe์€ ๊ฐ์ฒด์— ํ•ด๋‹น value๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ์žˆ๋‹ค๋ฉด true, ์—†๋‹ค๋ฉด false๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค. ๊ณต๋ถ€ํ•  ๋•Œ ์–ด๋–ค ๊ธฐ๋Šฅ์˜ ์›๋ฆฌ๋ฅผ ๋จผ์ € ๋ณด๊ธฐ๋ณด๋‹ค, ๊ทธ ๊ธฐ๋Šฅ์ด ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉ๋˜๊ณ , ๊ทธ ๊ธฐ๋Šฅ์˜ ์ทจ์ง€๋ฅผ ๋จผ์ € ์•Œ๊ธฐ๋ฅผ ๊ถŒ์žฅํ•œ๋‹ค.

Object.prototype.contain = function(needle){//๋ชจ๋“  ๊ฐ์ฒด์˜ ๋ถ€๋ชจObject์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๋งŒ๋“ ๋‹ค.
    for(var name in this) {//๋ฉ”์†Œ๋“œ ์•ˆ์—์„œ this๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์†Œ์†๋œ ๊ฐ์ฒด!
        //name์—๋Š” ๊ฐ๊ฐ์˜ key๊ฐ’์ด ๋‹ด๊ธฐ๊ฒŒ ๋œ๋‹ค.๋งˆ์น˜ index์ฒ˜๋Ÿผ ์‚ฌ์šฉ๋œ๋‹ค.
        if(this[name] === needle){
            return true;
        }
    }//๋๊นŒ์ง€ ๋‹ค ๋Œ์•˜๋Š”๋ฐ ์—†์œผ๋ฉด false๋ฅผ ๋ฆฌํ„ด.
    return false;
}
var o = {'name':'egoing','city':'seoul'}
console.log(o.contain('egoing'));

์ด๋Ÿฌํ•œ Object์˜ ํ™•์žฅ์€ ๋ชจ๋“  ๊ฐ์ฒด์— ์˜ํ–ฅ์„ ์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ์œ„ํ—˜ํ•˜๋‹ค.

a = ["egoing","leezche", "graphittie"]
o = Object {'name':'egoing','city':'seoul', contain:function}
for(var name in o){
    console.log(name);//name๊ณผ city, contain๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.
    console.log(o[name]);//egoing๊ณผ seoul, ๊ทธ๋ฆฌ๊ณ  contain ํ•จ์ˆ˜๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.
}

Object.prototype.contain์œผ๋กœ ์ถ”๊ฐ€ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ชจ๋“  ๊ฐ์ฒด์— ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ ์ƒ์†๋ฐ›์€ property์ธ contain์ด ์ถ”๊ฐ€๋œ๋‹ค.

hasOwnProperty๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.ํ•ด๋‹น ๊ฐ์ฒด๊ฐ€ ๋ถ€๋ชจ๋กœ๋ถ€ํ„ฐ ์ƒ์†๋ฐ›์€ property๊ฐ€ ์•„๋‹ˆ๋ผ,์ž์‹ ์˜ property๋กœ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•œ๋‹ค. ์ƒ์†๋ฐ›์€ ๊ฒƒ๊ณผ ์ง์ ‘์ ์œผ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

Object.prototype.contain = function(needle){//๋ชจ๋“  ๊ฐ์ฒด์˜ ๋ถ€๋ชจObject์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๋งŒ๋“ ๋‹ค.
    for(var name in this) {//๋ฉ”์†Œ๋“œ ์•ˆ์—์„œ this๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์†Œ์†๋œ ๊ฐ์ฒด!
        //name์—๋Š” ๊ฐ๊ฐ์˜ key๊ฐ’์ด ๋‹ด๊ธฐ๊ฒŒ ๋œ๋‹ค.๋งˆ์น˜ index์ฒ˜๋Ÿผ ์‚ฌ์šฉ๋œ๋‹ค.
        if(this[name] === needle){
            return true;
        }
    }//๋๊นŒ์ง€ ๋‹ค ๋Œ์•˜๋Š”๋ฐ ์—†์œผ๋ฉด false๋ฅผ ๋ฆฌํ„ด.
    return false;
}
var o = {'name':'egoing','city':'seoul'}
var a = {'egoing','leezche','graphittie'];

for(var name in a){//o๋กœ ์‹คํ–‰ํ•˜๋ฉด name๊ณผ city๋งŒ ์ถœ๋ ฅ๋œ๋‹ค.
    if(a.hasOwnProperty(name)){//contain์€ ์ œ๊ฑฐ๋˜๊ณ  0,1,2๋งŒ ์ถœ๋ ฅ๋œ๋‹ค.
        console.log(name);
    }
}

Last updated