//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);
}
}