JavaScript 实现对象继承的方式有多种,主要是 call / apply 方法和原型链方法这两种,实际情况中推荐使用两者的组合,即通过 call / apply 方法实现对象属性的继承,通过原型链方法实现对象方法的继承(根据每个对象的属性是各有一份,而方法是被所有对象所共用这一特征),下面逐一介绍:
- 对象冒充
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('Parent Name Zhangsan');
var child = new Child('Child Name LiSi','123');
parent.sayHello();
child.sayHello();
child.sayWorld();
- call 方法实现 js 对象的继承
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('Parent Name: Michael P');
var child = new Child('Child Name : Michael','mjj123');
parent.sayHello();
child.sayHello();
child.sayWorld();
- 使用 apply 方式实现 js 对象的继承
function Parent(userName) {
this.username = userName;
this.sayHello = function () {
alert(this.username);
}
}
function Child(userName,passWord) {
// apply 方式和 call 方式类似,但是传递的实际参数是一个包裹着实际参数的数组对象
Parent.apply(this,new Array(userName));
this.password = passWord;
this.sayWorld = function () {
alert(this.password);
}
}
var parent = new Parent('Parent Name: Michael P');
var child = new Child('Child Name: Michael','Michael 123');
parent.sayHello();
child.sayHello();
child.sayWorld();
- 使用原型链的方式实现 js 对象的继承,缺点(没法传参数)
function Parent() {
}
Parent.prototype.username = 'Parent Name : Michael';
Parent.prototype.sayHello = function () {
alert(this.username);
}
function Child(){
}
Child.prototype = new Parent('Parent Name: Michael P');
Child.prototype.password = 'Michael 123';
Child.prototype.sayWorld = function () {
alert(this.password);
}
var child = new Child();
child.sayHello();
child.sayWorld();
- 混合方式( call 方法实现属性继承,原型链方法实现方法继承)实现 js 对象的继承,推荐使用这种方式
function Parent(userName) {
this.username = userName;
}
Parent.prototype.sayHello = function () {
alert(this.username);
}
function Child(userName,passWord){
Parent.call(this,userName);
this.password = passWord;
}
Child.prototype = new Parent('Parent Name: Michael P');
Child.prototype.sayWorld = function () {
alert(this.password);
}
var child = new Child('Child Name : Michael','Michael 123');
child.sayHello();
child.sayWorld();
网友评论