Javascript中的类的创建
- /**
- * 工厂方法:
- * 存在问题:重复创建对象eat
- */
- function CreatePeople(name){
- var people=new Object();
- people.name=name;
- people.eat=function(){
- alert(this.name+' is eating !!')
- };
- return people;
- }
- /**
- * 构造函数法:
- * 存在问题:重复创建对象eat
- * 使用new 来创建对象,如:var p=new People('saber')
- * 在执行第一句代码前,先创建一个对象(并返回,所以构造函数最后无须return),只有用this才能访问该对象,
- *
- */
- function People(name){
- this.name=name;
- this.eat=function(){
- alert(this.name+' is eating !!')
- };
- }
- /**
- * 混合的构造函数/原型方式(推荐)
- */
- var People1=function (name){
- this.name=name;
- }
- People1.prototype={
- eat:function(){
- alert(this.name+' is eating !')
- }
- }
- /* 自定义构造函数为:initialize
- * 在使用new创建对象的时候,执行initialize函数,
- */
- var People11=function (){
- this.initialize.apply(this, arguments);
- }
- People11.prototype={
- initialize:function(name){
- this.name=name;
- alert(' Initializing Ok !!');
- },
- eat:function(){
- alert(this.name+' is eating !')
- }
- }
- /* 有以上基础,如果我们要以一种统一的方式来定义类,该如何呢?
- * 像java中定义类都采用Class关键字一样,而在JS中,没有类这个概念,
- * 那么我们首先声明一个对象MyClass
- */
- var MyClass=function(){
- return function(){//闭包
- this.initialize.apply(this, arguments);
- }
- }
- /*
- * 定义类:
- */
- var ClassOne=MyClass();
- ClassOne.prototype={
- initialize:function(name){
- this.name=name;
- alert(this.name+' initializing Ok !')
- },
- methodOne:function(){
- alert("My name is:" + this.name);
- }
- }
- var ClassTwo=MyClass();
- ClassTwo.prototype={
- initialize:function(name){
- this.name=name;
- },
- methodTwo:function(){
- alert("My name is:" + this.name);
- }
- }
- /**
- * 采用prototype.js,它的方法和我们上边的一样:
- * var Class = {
- * create: function() {
- * return function() {
- * this.initialize.apply(this, arguments);
- * }
- * }
- *}
- */
- var People2=Class.create();
- People2.prototype={
- //自定义的构造函数:initialize
- initialize:function(name,sex){
- this.name=name;
- this.sex=sex;
- },
- eat:function(){
- alert(this.name+' is eating ');
- },
- showSex:function (){
- alert(this.name+'\'s sex is :'+this.sex);
- }
- }