Fork me on GitHub

《JavaScript核心及实践》

JavaScript语言特性

JavaScript是一门动态的,弱类型,基于原型的动态语言。用一句话“一切皆对象”描述在好不过了。

动态性指要为属性赋值时,不必先创建一个字段,只需在使用时赋值即可。
弱类型指数据类型无需声明时指定,解释器会根据上下文进行实例化。

对象与JSON

JSON是JavaScript中对象的字面量,是对象的表示方法,通过使用JSON,可以减少中间变量,使代码更加清晰直观。使用JSON,可以动态创建对象,而不必通过类来实例化,提高了编码效率。

原型对象与原型链

原型是JavaScript特有的概念,通过原型,可以实现继承,从而体现对象的层次关系。由于本身基于原型,使得每个对象都有一个prototype值,而这个prototype本身就是就是一个对象,因此本身就有自己的原型,这样就构成了一个链结构。

当访问一个属性时,解析器需要从下向上遍历这个链结构,直到该属性,若此对象没有该属性,则返回undefined。比如下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//声明一个对象base
function Base(name){
this.name=name;
this.getName=function (){
return this.name;
}
}
//声明一个child
function Child(id){
this.id=id;
this.getId=function (){
return this.id;
}
}
//将child原型指向base对象
Child.prototype=new Base("base");
//实例化child对象
var c=new Child("child");
console.log(c.getId());
console.log(c.getName()); //通过原型继承到getName方法

继承与重载

1
2
3
4
5
6
7
8
9
10
11
12
function person(name,age){
this.name=name;
this.age=age;
this.getName=function (){
return this.name;
}
this.getAge=function (){
return this.age;
}
}
var Tom=new person("Tom",22);
var Alice=new person("Alice",20);

通过原型链,可以实现继承/重载等面向JavaScript代码,当然这个机制并非基于类,而是基于原型。

this指针

在JavaScript中,this表示当前上下文,是对调用者的引用。这里要注意,this值并非函数如何声明而确定,而是在调用时确定。

使用对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function address(street,num){
this.street=street || "This is a road";
this.num=num || 22;
this.toString=function (){
return this.street+this.num;
}
}
function person(name,age,addr){
this.name=name || "unknown";
this.age=age;
this.addr=addr || new address(null,null);
this.getname=function (){
return this.name;
}
this.getage=function (){
return this.age;
}
this.getaddr=function (){
return this.addr.toString();
}
}
var John=new person('John',22,new address("road","111"));
var Alice=new person('Alice',12);
console.log(John.getname());
console.log(John.getage());
console.log(John.getaddr());
console.log(Alice.getname());
console.log(Alice.getage());
console.log(Alice.getaddr());

JSON及其使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//对象表示法
var obj={
name:"张三",
age:"22",
birthday: new Date(1999,9,9),
addr:{
street:"road",
num:222
}
}
//多个返回值
function position(left,top){
this.left=left;
this.top=top;
return {x:this.left,y:this.top}
}
var pos=position(3,4);
//遍历js对象
var style={
border:"1px solid red",
color: "orange"
}
for(var i in style){
$('ele').css(i,style[i])
}

未完待续。。。

据说帅的人都赏给博主几块钱零花钱。