close
javascript 建立 class 方式有很多種:
1. 將程式碼放入 function 內
function Dog () {
this.name = "";
this.position = 0;
this.bark = function (){
alert("wuff");
};
this.walk = function(){
this.position += 1;
alert("position = "+this.position);
}
this.getName = function (){
return this.name;
}
}
var dog = new Dog();
dog.name = "Ralph";
dog.bark(); //Popup box with "wuff"
dog.walk(); //Position increases by 1;
alert(dog.getName()); //Outputs dog's name*/
2. 將程式碼放入 object 內
var Dog = {
name : "",
position: 0,
bark : function(){ alert("wuff") },
walk : function(){
this.position += 1;
alert("position = "+this.position);
},
getName : function(){
return this.name
}
}
Dog.name = "Ralph";
Dog.bark(); //Popup box with "wuff"
Dog.walk(); //Position increases by 1;
alert(Dog.getName()); //Outputs dog's name
3. 使用 prototype 建立 class
function Dog (){} Dog.prototype.name = "";< Dog.prototype.position = 0; Dog.prototype.bark = function (){ alert("wuff"); } Dog.prototype.walk = function (){ this.position += 1;
alert("position = "+this.position);
}
Dog.prototype.getName = function(){
return this.name;
}
var dog = new Dog();
dog.name = "Ralph";
dog.bark(); //Popup box with "wuff"
dog.walk(); //Position increases by 1;
alert(dog.getName()); //Outputs dog's name
// Here is a Puppy class to show how inheritance is done
// It inherits all the methods of the Dog class, but overwrites the bark method for a more puppy like bark
function Puppy (){}
Puppy.prototype = new Dog();
Puppy.prototype.bark = function (){
alert("Yelp");
}
var puppy = new Puppy();
puppy.name = "Ralph";
puppy.bark(); //Popup box with "Yelp"
puppy.walk(); //Position increases by 1;
alert(puppy.getName()); //Outputs puppy's name
文章參考來源:http://www.devirtuoso.com/2009/09/object-oriented-programming-with-javascript/
全站熱搜
留言列表