Javascriptにおけるクラスの定義
2591 ワード
/**
* :
* : 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);
}
}