1.类的定义以及基于类创建示例对象:
function Dog(){
var name=fido;
}
var dog=new Dog();
2.定义公有属性和私有属性
定义私有属性:
1.函数中:var定义
2.函数外:对象.属性名定义
function Dog(){
var name=fido;
}
var dog=new Dog();
dog.weight=80;
alert(dog.weight);//80
var dog1=new Dog();
alert(dog1.weight);//undefined(weight为私有属性)
定义公有属性:
1.函数中:this.属性名定义
2.函数外:函数名.prototype.属性名=默认值
function Dog(){
var name=fido;
this.age=5;//定义公有属性
}
Dog.prototype.height=50;//定义公有属性
var dog=new Dog();
dog.weight=80;
alert(dog.weight);//80
alert(dog.age);//5
alert(dog.height);//50
3.定义公有方法和私有方法
定义私有方法:
1.函数中:var 方法名=function() { }
2.函数外:对象名.方法名=function(){ }
定义公有方法:
1.函数中:this.方法名=function() { }
2.函数外:函数名.prototype.方法名=function(){ }
function Dog(){
var show=function(){
alert("Show time!");
}
this.display=function(){
show();
}
}
var dog=new Dog();
dog.show();//无此方法
dog.display();
Dog.prototype.bark=function() {
alert("Wang Wang!");
}
dog.bark();
4.静态属性和静态方法
定义静态属性和方法都要用函数名来定义,调用时只能用函数名来调用,不能用对象调用。
function Dog(){
}
Dog.name="fido";
Dog.show=function(){
alert("此为静态方法");
}
alert("Dog.name");
Dog.show();
var dog=new Dog();
alert("dog.name");//undefined
dog.show();//无此方法
5.构造函数
函数名不能重复,因为先定义的函数永远无法调用。
6.原型(prototype)方式声明属性与方法
2,3有说明,不再赘述
7.直接用Object或函数对象加属性和方法
创建Javascript对象的三种方式:
1.采用new函数名();
2.采用new Object();//了解
3.采用json格式定义
function Dog() {};
var dog=new Dog();
var obj=new Object();
obj.name="fido";
var json={"a":China;"b":America;"c":Canada};
var json1={1:China;2:America;3:Canada};//不加""
alert(json.a);
alert(json["b"]);
alert(json1[2]);//不加"",也不能用json1."2"
var(i in json){
alert(i+":"+json[i]);//打印所有值,但不能用json.i
}