在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称"实例")共有的属性和方法。JavaScript语言里是没有类的概念的,但是我们通过以下方法也可以模拟出类。
一.创建类:
1.利用function关键字和this关键字:
/**
* 定义类 User
* 通过function ,this关键字实现。
* @returns
*/
function User(){
this.name="123";
this.getName=function(){
return this.name;
}
}
//使用类
var user=new User();
alert(user.getName());
2.原型方法:
利用prototype关键字和this关键字实现。
/**
* 定义类 User
* 通过function ,this关键字实现。
* @returns
*/
function User(name){
this.name=name;
this.age=1;
}
User.prototype={
getName: function(){
return this.name;
}
}
var user = new User('hello');
alert(user.getName());//访问方法
alert(user.name);//访问属性
alert(user.age);//访问属性
3.利用Object.create()方法构造
为了解决"构造函数法"的缺点,更方便地生成对象,Javascript的国际标准ECMAScript第五版(目前通行的是第三版),提出了一个新的方法Object.create()。
User={
name:'hello',
getName:function(){
return this.name;
}
}
//使用
var user=Object.create(User);
alert(user.getName());
二.继承:
1.利用prototype关键字
function extend(Sub,Sup) {
//Sub表示子类,Sup表示超类
// 首先定义一个空函数
var F = function(){};
// 设置空函数的原型为超类的原型
F.prototype = Sup.prototype;
// 实例化空函数,并把超类原型引用传递给子类
Sub.prototype = new F();
// 重置子类原型的构造器为子类自身
Sub.prototype.constructor = Sub;
// 在子类中保存超类的原型,避免子类与超类耦合
Sub.sup = Sup.prototype;
if(Sup.prototype.constructor === Object.prototype.constructor) {
// 检测超类原型的构造器是否为原型自身
Sup.prototype.constructor = Sup;
}
}