您的位置:首页 > Web前端 > JavaScript

JavaScript继承的几种方式解析

2013-10-20 12:53 501 查看
(一).对象冒充
概念:新的类冒充旧的类(旧的类必须采用构造函数的方式)
示例代码:
//父类
function people(name,age){
this.name = name;
this.age = age;
this.say = function(){
alert("My name is "+this.name);
};
}
//创建一个对象
var Wen = new people("xiaowen","21");
Wen.say();
//子类
function chinese_people(name,age){
this.A = people;//冒充people这个对象
this.A (name,age);//继承people
delete this.A;//必须删除继承.防止覆盖被继承的类的属性和方法
this.area = function(){
alert("I am in china");
};
}
//创建一个chinese_people对象
Var marry = new chinese_people("xiaoxiao","20");
marry.say();
marry.area();
alert(marry.name);
另外,对象冒充也支持多继承,这里不做详解。
(2).call方法

概念:

调用一个对象的一个方法,以另一个对象替换当前对象。



function Rect(width, height){
this.width = width;
this.height = height;
this.area = function(){return this.width*this.height;};
}

function myRect(width, height, name){
Rect .call(this,width,height);//应用call方法
this.name = name;
this.show = function(){
alert(this.name+” with area:”+this.area());
}
}

(3)apply方法

/*定义一个人类*/
function Person(name,age)
{
this.name=name;
this.age=age;
}
/*定义一个学生类*/
functionStudent(name,age,grade)
{
//this在创建对象的 时候是Student
//arguments:参数数组,即["name","age","grade"]
Person.apply(this,arguments);
this.grade=grade;
}
//创建一个学生类
var student=new Student("qian",21,"一年级");
//测试
alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);


(4).原型模式

概念:

是指利用了prototype或者说以某种方式覆盖了prototype,从而达到属性方法复制的目的。
prototype网上的三种理解:


1:通过构造函数创建的普通对象,通过其constructor属性引用它的构造函数对象,从而间接引用(拥有)了构造对象中的prototype对象;



2:构造函数创建对象时,copy prototype中的属性和代码给所创建的对象。从而使创建的对象拥有了prototype中的所有功能和属性;
3:构造函数在创建对象时,把构造函数中的prototype引用赋给创建的普通对象;也就是说由构造函数创建的对象,都有一个指针指向prototype对象;

function Person(){
this.name = “Mike”;
this.sayGoodbye = function(){alert(“GoodBye!”);};
}

Person.prototype.sayHello = function(){alert(”Hello!”);};

function Student(){}
Student.prototype = new Person();

function Person(name){
this.name = name;
}

function Student(name,id){
this.id = id;
}

Student.prototype = new Person(this.name);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: