面向?qū)ο蟮囊粋€簡單的例子:
<script>
/*構(gòu)造函數(shù)(函數(shù)名采用大駝峰)*/
function CreatePerson(name,age){
this.name = name;
this.age = age;
}
CreatePerson.prototype.showName = function(){
return this.name;
};
CreatePerson.prototype.showAge = function(){
return this.age;
};
var p1 = new CreatePerson('aaa',12);
var p2 = new CreatePerson('bbb',18);
console.log('p1的名字:'+p1.showName());//aaa
console.log(p1.showAge === p2.showAge);//true
/*instanceof檢查父級实苞、父級的父級...辆飘,正確返回true,不正確返回false*/
console.log("instanceof檢查父級升酣、父級的父級...檬洞,正確返回true,不正確返回false");
console.log(p1 instanceof CreatePerson);//true
console.log(p1 instanceof Object);//true
console.log(CreatePerson instanceof Object);//true
/*這里有一個坑狡恬,p1不是Function的子集珠叔,但是CreatePerson是*/
console.log(p1 instanceof Function);//false
console.log(CreatePerson instanceof Function);//true
/*constructor只檢查父級*/
console.log("constructor只檢查父級");
console.log(p1.constructor == CreatePerson);
console.log(p1.constructor == Object);
</script>
像數(shù)組Array、Date等封裝好的也有這樣的問題弟劲,比如數(shù)組:
//var arr = [1,2];
var arr=new Array(1,2);
console.log(arr instanceof Array);//true
console.log(Array instanceof Object);//true
console.log(arr instanceof Object);//true
console.log(arr instanceof Array);//true
console.log(Array instanceof Function);//true
console.log(arr instanceof Function);//false
繼承
<script>
function Person(name,age){
this.name='are you die?'+name;
this.age=age;
};
Person.prototype.showName=function(){
return this.name;
};
Person.prototype.showAge=function(){
return this.age;
};
function Worker(name,age,job){
/*屬性繼承祷安,這三種方法都可以*/
//Person.call(this,name,age);
//Person.apply(this,[name,age]);
Person.apply(this,arguments);
this.job=job;
};
Worker.prototype.showJob=function(){
return this.job;
};
//方法繼承一
Worker.prototype=new Person();
/*new過以后父級指向變成了person,所以需要指定一下父級*/
Worker.prototype.constructor=Worker;
/*方法繼承二*/
/*for(var name in Person.prototype){
Worker.prototype[name]=Person.prototype[name];
}*/
var w1=new Worker('小明','18','醫(yī)生');
//alert(w1.showJob());
alert(w1.showAge());
//alert(w1.constructor==Person);//false
alert(w1.constructor==Worker);//true
</script>