0, -0, null, "", false, NaN, undefined는 false이며, 나머지는 몽땅 true
Object 객체는 top-level 의 Global 객체이고, empty 객체이다.
프로퍼티 :
constructor 생성자 메서드 명시
prototype 추가 메서드 및 프로퍼티 명시
메서드 :
hasOwnProperty(): 프로퍼티 존재 boolean으로 return;
toString(): 객체의 상태를 String return;
isPrototypeOf(o) : 다른 객체로부터 확장 되었는지 boolean return;
다른 객체들 :
String Number Math Array Date
JAVASCRIPT Object Instance 만들기
var o1 =new String("Hello My Girl");
var o2 =new Number(1234);
메모리 해제: o1 = null;
예제
String.prototype.myComment;
String.prototype.getLength = function(){ return this.length;}
String prototype.toString = function(){ return "상현의 말: "+ 소냐.valueOf();}
var o = new String("hello my girl!");
o.myComment = "this is Object";
alert(o.myComment);
alert(o.getLength());
alert(o);
세줄 요약
1.인스턴스가 메모리에 자리 잡아야( new를 해줘야) 진정한 객체다.
2.prototype은 개짱이다.
3.자바스크립트에서도 오버라이딩이 가능하다.(prototype 통해)
JS에서의 Object란? Unique Identity(이름), State(어트리뷰트), Behavior(메서드) 를 가진 사용자 정의 데이터
사용자 객체를 만들어 보자.
function myClass(p)
{
this.Comment = "사용자 정의 Object";
this.v1= p;
v2= " this is v2";
}
function myClass_toString()
{
return "v1=" +this.v1;
}
function myClass_setValue(p)
{
this.v2=p;
}
function myClass_getValue()
{
return this.v2;
}
myClass.prototype.toString = myClass_toString;
myClass.prototype.setValue = myClass_setValue;
myClass.prototype.getValue = myClass_getValue;
myClass.prototype.resetValue = function(){ this.v1 = nulll this.v2 = null;}
var one= new myClass("1");
alert(one.v1);
alert(one.v2);
alert(o);
자바스크립트에서는 function도 객체이다.
myClass(){} 를 보면 어트리뷰트는 (comment v1 v2) 총 3개이며, 매서드는 prototype로 확장한다.
this.comment, this.v1 과 v2의 차이는 public과 private의 차이이다. this를 사용하면 Public, 사용하지않으면 Private이다.
setValue getValue는 myClass_get,setValue;
resetValue = function(){~~~} 의 차이는
함수의 이름으로 할당하는 경우는 함수 포인터를 할당하는 것이고, resetValue는 함수 리터럴을 이용해 함수를 할당한 것.
-> 자바스크립트 엔진이 실행시점에 함수 포인터가 가리키는 함수 내용을 복사해서 끼워 넣는다.
상속(inheritance) 1.3Version이상부터 지원
function Father(p1,p2){
this.FatherMoney = p1 *p2;
}
/*
어트리뷰트로 FatherMoney를 가지고 있고 Say라는 메서드를 가진다.
*/
Father.prototype.Say = function()
{
alert("내 용돈은 :"+this.FatherMoney+"원 ");
}
function Son(p){
Father.call(this.p,2);
this.SonMoney = p;
}
Son.prototype = new Father();
Son.prototype.Say = function()
{
alert("상속받은 자의 용돈은 :"+this.SonMoney +"원");
}
Son.prototype.FatherSay = function(){Father.prototype.Say.call(this)}
/*
Father를 상속받고, Say를 재정의함
*/
var one = new Son(100);
one.Say();
one.FatherSay();
Father.call(this.p,2);
call, apply는 다른 Context의 객체를 사용 할 수 있게 해준다.
상위인자와 하위객체생성자의 인자 집합이 동일하다면 apply, 서로 다르다면 call을 사용한다.
여기서는 call을 사용해 서로 다른 인자집합을 가지는 것을 연습.
해당 객체를 사용하는 Context가 자신이기 때문에, 첫 번째 인자는 무조건 this이다. 이 선언으로 Father의 모든 것을 사용하겠다는 사실을 자바스크립트 엔진에게 알려주게 된다.
Son.prototype = new Father();
부모 객체의 instance를 생성한 후에, 자식 객체를 생성한다.
Son.prototype.FatherSay = function(){Father.prototype.Say.call(this);}
super키워드 지원이 안되기 때문에, 부모 메서드를 호출할 때 이렇게 써줌.
ㅇ