第一种方式:
定义类:
function Fruit(fruitname) {
this.name = fruitname;
this.color = "";
this.getInfo = function() {
return "This fruit is an " + this.color + ' ' + this.name;
};
}
或者把里面的方法(method)放在外面:
function fruit(fruitname) {
this.name = fruitname;
this.color = "red";
this.getInfo = getInfo_fruit();
};
}
function getInfo_fruit() {
return "This fruit is a " + this.color + ' ' + this.name;
};
引用类,建立对象:
var fruit = new fruit('apple');
fruit.color = "red";
alert(fruit.getInfo());
第二种方式:
定义类:
var fruit = new function() {
this.name = "";
this.color = "";
this.getInfo = function () {
return "This fruit is a " + this.color + ' ' + this.name;
};
}
实例在上面已经建立,可以直接使用:
fruit.name = "apple";
fruit.color = "red";
alert(fruit.getInfo());
第三种方式:
定义类:
var fruit = {
name: "",
color: "",
getInfo: function () {
return "This fruit is a " + this.color + ' ' + this.name;
}
}
使用:
fruit.name = "apple";
fruit.color = "red";
alert(fruit.getInfo());
第四种方式,有种说法说这种比较好,把方法放在外面,定义为prototype,这样每次对类建立对象时,不会对里面的方法在内存中建立实例,比如下面的方式:
function Fruit(){
this.info = "This is a red apple";
}
Fruit.prototype.getInfo = function (){
alert(this.info) ;
}
引用方式:
var fruit = new Fruit();
alert(fruit.getInfo);