js火了好长时间了,一直也没去学习一下,无意中发现一片快速指南 照着做了一下 发现原来很简单,现记录下来 作为备忘吧
JSON
json相当于java中的对象:

var user = {
    username:'xuly',
    sex:'男',
    sayHello:function(){
        alert('hello world');
    }
};
user.sayHello();

输出:hello world
在js中函数也是一个对象,你可以传递一个函数作为参数,就像传递一个字符串一样

数组
这两句是一样的
var a = new Array();  //alert(a.size) == 0
var b = [];           //alert(b.size) == 0;

b = ['hello', 34, 'java script'];
b[10] = 32; //alert(b.length) == 11

数组元素可为任何类型 数组型 字符串都是合法的

另外数组下标可以为字符串,主要用于访问对象的属性 如下例
var user = {};
user['username'] = 'xuly';
user['sex'] = '男';
user['sayHello']=function(){
    alert('hello world');
};

这效果跟上面json的user对象是一样的
user['sayHello'](); 
user.sayHello();

这两句也是做同一件事的



js中类的概念是最重要的  下面我们来认识一下类
//定义一个类 :Person
var Person = function(name, age){
    this.name = name;
    this.age = age;
};

var aPerson = new Person('xuly', 20);
alert(aPerson.name); //  output 'xuly'

可以看到js的类就是一个函数, 不同的是这个函数用到了this关键字来定义类属性
上例中只是声明了属性 并没有声明方法 方法是这样声明的
Person.prototype.sayHello = function(){
    return 'hello ' + this.name;
};


如果采用prototype.js框架来定义一个类将更加简单
var Persion = Class.create();
Persion.prototype = {
   //constructor
    initialize:function(name, age){
        this.name = name;
        this.age = age;
    },
    sayHello: function(){
        return 'hello ' + this.name;
    }
};



原文:http://www.sergiopereira.com/articles/advjs.html
评论
发表评论

您还没有登录,请登录后发表评论

xly_971223
搜索本博客
博客分类
我的相册
C5b0e206-307c-3f61-aa60-9cfd71c61bb3-thumb
u=3528569133,1587051000&gp=38.jpg
共 2 张
最近加入圈子
存档
最新评论