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
Was this helpful?