1) 對象冒充
//繼承第一種方式:對象冒充
function Parent(username)
{
this.username = username;
this.sayHello = function()
{
alert(this.username);
}
}
function Child(username, password)
{
//下面三行代碼是最關鍵的代碼
this.method = Parent;
this.method(username);
delete this.method;
this.password = password;
this.sayWorld = function()
{
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "1234");
parent.sayHello();
child.sayHello();
child.sayWorld();
2) call方法方式。
call方法是Function對象中的方法,因此我們定義的每個函數都擁有該方法。
可以通過函數名來調用call方法,call方法的第一個參數會被傳遞給函數中的this,
從第2個參數開始,逐一賦值給函數中的參數。
//繼承的第二種實現方式,call方法方式,Function對象中的方法
function test(str, str2)
{
alert(this.name + ", " + str + ", " + str2);
}
var object = new Object();
object.name = "zhangsan";
//test.call相當於調用了test函數
test.call(object, "hello", "world"); //將object賦給了this
*************************
//使用call方式實現對象的繼承
function Parent(username)
{
this.username = username;
this.sayHello = function()
{
alert(this.username);
}
}
function Child(username, password)
{
Parent.call(this, username);
this.password = password;
this.sayWorld = function()
{
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");
parent.sayHello();
child.sayHello();
child.sayWorld();
3) apply方法方式
//使用apply方法實現對象繼承
function Parent(username)
{
this.username = username;
this.sayHello = function()
{
alert(this.username);
}
}
function Child(username, password)
{
Parent.apply(this, new Array(username));
this.password = password;
this.sayWorld = function()
{
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");
parent.sayHello();
child.sayHello();
child.sayWorld();
4)原型鏈方式(無法給建構函式傳參數)
//使用原型鏈(prototype chain)方式實現對象繼承
function Parent()
{
}
Parent.prototype.hello = "hello";
Parent.prototype.sayHello = function()
{
alert(this.hello);
}
function Child()
{
}
Child.prototype = new Parent();
Child.prototype.world = "world";
Child.prototype.sayWorld = function()
{
alert(this.world);
}
var child = new Child();
child.sayHello();
child.sayWorld();
5)混合方式(推薦)
//使用混合方式實現對象繼承(推薦)
function Parent(hello)
{
this.hello = hello;
}
Parent.prototype.sayHello = function()
{
alert(this.hello);
}
function Child(hello, world)
{
Parent.call(this, hello);
this.world = world;
}
Child.prototype = new Parent();
Child.prototype.sayWorld = function()
{
alert(this.world);
}
var child = new Child("hello", "world");
child.sayHello();
child.sayWorld();