JavaScript中的类与实例实现方法
本文实例讲述了JavaScript中的类与实例实现方法。分享给大家供大家参考。具体如下:
JavaScript中没有父类,子类的概念,也没有class和instance的概念,全靠prototypechain来实现继承.当查找一个对象的属性时,JavaScript会向上遍历prototypechain,直到找到对应的属性为止.有几种方法,可以使得JavaScript模拟出class和instance的概念.
1.直接使用构造函数来创建对象,在构造函数内部使用this指代对象实例.
functionAnimal(){
this.name="animal";
}
Animal.prototype.makeSound=function(){
console.log("animalsound");
}
[Function]
varanimal1=newAnimal();
animal1.name;
'animal'
animal1.makeSound();
animalsound再看另外一个例子:
functionPoint(x,y){
this.x=x;
this.y=y;
}
Point.prototype={
method1:function(){console.log("method1");},
method2:function(){console.log("method2");},
}
{method1:[Function],method2:[Function]}
varpoint1=newPoint(10,20);
point1.method1();
method1
point1.method2();
method2以上,先指定好一个构造函数对象的prototype属性.然后new一个该对象实例,即可调用prototype中指定的方法.
2.使用Object.create()方法来创建对象
varAnimal={
name:"animal",
makeSound:function(){console.log("animalsound");},
}
varanimal2=Object.create(Animal);
animal2.name;
'animal'
console.log(animal2.name);
animal
animal2.makeSound();
animalsound该方法,比构造函数的方法更简便,但不能实现私有属性和私有方法,且实例对象之间不能共享数据,对class的模拟仍不够全面.
3.荷兰程序员GabordeMooij提出的极简主义法(minimalistapproach).推荐用法.
varAnimal={
init:function(){
varanimal={};
animal.name="animal";
animal.makeSound=function(){console.log("animalsound");};
returnanimal;
}
};
varanimal3=Animal.init();
animal3.name;
'animal'
animal3.makeSound();
animalsound不使用prototype和this,仅需要自定义一个构造函数init.继承的实现也很简单.
varCat={
init:function(){
varcat=Animal.init();
cat.name2="cat";
cat.makeSound=function(){console.log("catsound");};
cat.sleep=function(){console.log("catsleep");};
returncat;
}
}
varcat=Cat.init();
cat.name;//'animal'
cat.name2;//'cat'
cat.makeSound();//类似于方法的重载
catsound
cat.sleep();
catsleep私有属性和私有方法的使用:
varAnimal={
init:function(){
varanimal={};
varsound="privateanimalsound";//私有属性
animal.makeSound=function(){console.log(sound);};
returnanimal;
}
};
varanimal4=Animal.init();
Animal.sound;//undefined私有属性只能通过对象自身的方法来读取.
animal.sound;//undefined私有属性只能通过对象自身的方法来读取
animal4.makeSound();
privateanimalsound只要不是定义在animal对象上的属性和方法都是私有的,外界不能访问.
类与实例之间,可以做到数据共享.
varAnimal={
sound:"commonanimalsound",
init:function(){
varanimal={};
animal.commonSound=function(){console.log(Animal.sound);};
animal.changeSound=function(){Animal.sound="commonanimalsoundchanged";};
returnanimal;
}
}
varanimal5=Animal.init();
varanimal6=Animal.init();
Animal.sound;//可以视为类属性
'commonanimalsound'
animal5.sound;//实例对象不能访问类属性
undefined
animal6.sound;
undefined
animal5.commonSound();
commonanimalsound
animal6.commonSound();
commonanimalsound
animal5.changeSound();//修改类属性
undefined
Animal.sound;
'commonanimalsound'
animal5.commonSound();
commonanimalsound
animal6.commonSound();
commonanimalsound如Animal.sound就是类与实例的共有属性,可以视为类属性和类方法.
若一个实例修改了该共有属性,则该类和其他实例的共有属性也对应修改了.
综上,就是JavaScript中模拟的class和instance的概念和用法.
希望本文所述对大家的javascript程序设计有所帮助。