您的位置:首页 > Web前端 > JavaScript

Javascript 创建对象的四种方法,类的三种属性,三种方法

2017-07-13 11:16 831 查看
1. 使用Jeson创建新对象

var point={x:1,y:2};
var point2={x:point.x, y:point.y+2};
var person={'the name':'peter', 'the age': '23'};
document.write(point2.y);
document.write(person['the name']);


Jeson表达式的每次运算都创建并初始化一个新对象。也就是说,如果在一个重复

调用的函数中的循环体内使用了Jeson表达式,它将创建很多新对象.

2. 使用 new 创建对象

function Person(name,age){ //声明类和类的构造函数
this.name=name; //类的属性
this.age=age;
this.sayHello=function(){ //类的方法
document.writeln("Hello I'm " + this.name);
}
this.setName=function(name){
this.name=name;
}
this.setAge=function(age){
this.age=age;
}
}

Person.Max_Age=120; //类的静态属性

Person.cry=function(){ //类的静态方法
document.writeln('www...'); //所有Person的哭声是一样的
}

Person.prototype.sex='male'; //类的原型属性,相当于把sex作为非静态属性拷贝到类的定义中

Person.prototype.run=function(){ //类的原型方法,相当于把run方法作为非静态方法拷贝到类的定义中
document.writeln('running...');
}

var tom = new Person('tom',23);
document.writeln(tom.age); //访问类的属性
document.writeln(Person.Max_Age); //访问类的静态属性
document.writeln(tom.sex); //访问类的原型属性
tom.sayHello(); //访问类的方法
tom.run(); //访问类的原型方法
Person.cry(); //访问类的静态方法


3.使用prototype创建对象

function Chinese(){
this.sayHello=function(){ //覆盖Person的sayHello()方法
document.writeln('你好! 我是' + this.name);
}
}
//Chinese继承(准确的说是拷贝,因为Person也可以拷贝Chinese的属性和方法)了Person的属性和方法
Chinese.prototype=new Person();
//或者Chinese.prototype=new Person('xiao',21);
var xiaomin = new Chinese();
xiaomin.setName('xiaomin');
xiaomin.setAge(21);
document.writeln(xiaomin.age); //访问父类的属性
//document.writeln(Chinese.Max_Age); //“不能”访问父类的静态属性
document.writeln(xiaomin.sex); //访问父类的原型属性
xiaomin.sayHello(); //访问父类的方法
//Chinese.cry(); //“不能”访问父类的静态方法
xiaomin.run(); //访问父类的原型方法
document.writeln(Chinese.prototype.name);//=>tom 访问prototype中的变量,原型中的变量没有改变。


4.Object.create方法创建对象

var peter = Object.create(tom);
document.writeln(peter.age); //访问类的属性
document.writeln(peter.sex); //访问类的原型属性
peter.sayHello(); //访问类的方法
peter.run(); //访问类的原型方法
peter.setAge(18);
document.writeln(peter.age); //peter的属性发生了改变
document.writeln(tom.age); //tom的属性没有改变
peter.weight=120; //给peter增加新的属性
document.writeln(peter.weight); //peter新增了属性
document.writeln(tom.weight); //tom没有新增属性
tom.high=180; //给tom增加新的属性
document.writeln(peter.high); //peter的high=180
document.writeln(tom.high); //tom的的high=180


以上实验说明Object.create创建的对象和prototype创建的对象比较类似,有拷贝/继承的味道

5. 遍历类的属性和方法

//遍历对象的非静态属性和方法,以及原型属性和方法
var tom = new Person('tom',2
ad3e
3);
var p='';
for(p in xiaomin){
document.writeln(p+'='+tom[p]);
}
//遍历类的静态属性和方法
var p='';
for(p in Person){
document.writeln(p+'='+tom[p]); //可以获取对象的属性名,但无法获取它的值
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: