上一篇:神木县委书记被“贬” vs. 宜黄县委书记留任
下一篇:javascript的缩写词 vs. 全称
4种方式建立javascript的类
米娅 2010年9月27日 13:46:42

第一种方式:
定义类:
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);
       


共1页
相关链接
1. Drupal 7.19: Notice: Undefined index: description in simpletest_test_form()
2. 手机卡成功剪卡装进iphone 5
3. iPhone 5 YouTube视频无法播放(已解决)
4. 整站下载工具WebZip
5. 如何用Adobe Flash CS4和ActionScript 3.0添加超级链接(附代码)
6. 学习Adobe Flash ActionScript的推荐链接
7. 网页右键禁用JavaScript代码
8. 下载Eclipse的链接
9. 应用Ajax、PHP、javascript来实现异步操作
10. 加拿大邮票: Canadian Diplomacy (2009)
11. 在eBay上卖东西(7):如何合并邮包优惠邮费(combine the shipping fee)
12. 在eBay上卖东西(3):什么是Print a shipping label
13. Boxing Day的多伦多Nathan Phillips广场(摄影)
14. iphone里的内置指南针定位
15. javascript中的冒号作什么用
16. 用javascript判断字符串是否为正整数