Javascript基礎(三)対象継承
2529 ワード
私のCSDNブログの住所: http://blog.csdn.net/caicongyang
1.相手を偽る
1.相手を偽る
//
function Parent(username)
{
this.username = username;
this.sayName = function()
{
alert(this.username);
};
}
function Chlid(username,age){
this.method = Parent;
this.method(username);
delete this.method;
this.age = age;
this.sayAge = function (){
alert(this.age);
};
}
var parent = new Parent("Tom1");
parent.sayName();
var chlid = new Chlid("Tom2","23");
chlid.sayName();
chlid.sayAge();
2.コール方式//call
function Parent(username)
{
this.username = username;
this.sayName = function()
{
alert(this.username);
};
}
function Chlid(username,age){
Parent.call(this, username);
this.age = age;
this.sayAge = function(){
alert(this.age);
};
}
var parent = new Parent("C");
parent.sayName();
var chlid = new Chlid("C++","25");
chlid.sayName();
chlid.sayAge();
3.アプリ方式//apply
function Parent(username)
{
this.username = username;
this.sayName = function()
{
alert(this.username);
};
}
function Chlid(username,age){
Parent.apply(this, new Array(username));
this.age = age;
this.sayAge = function(){
alert(this.age);
};
}
var parent = new Parent("C");
parent.sayName();
var chlid = new Chlid("JAVA","25");
chlid.sayName();
chlid.sayAge();
4.propotype chainプロトタイプチェーンの方式//propotyes chain
function Parent(){
}
Parent.prototype.name = "lisi";
Parent.prototype.sayName = function(){
alert(this.name);
};
function Child(){
}
Child.prototype = new Parent();
Child.prototype.age = "18";
Child.prototype.sayAge = function(){
alert(this.age);
};
var parent = new Parent();
parent.sayName();
var Child = new Child();
Child.sayName();
Child.sayAge();
5.混合方式(推奨)// ( )
function Parent(name){
this.name = name;
}
Parent.prototype.sayName = function(){
alert(this.name);
};
function Child(name,age){
Parent.call(this, name);
this.age = age;
};
Child.prototype = new Parent();
Child.prototype.sayAge = function(){
alert(this.age);
};
var parent = new Parent("c");
parent.sayName();
var Child = new Child("java","13");
Child.sayName();
Child.sayAge();
私のCSDNブログの住所: http://blog.csdn.net/caicongyang