一、简介
在JS中,一切皆为对象。字符串、数组、函数等都是对象。
二、常见的js功能
/**
* 显示对象的属性方法一
* @returns
*/
function myFunction1(){
person = {firstname:"David",lastname:"Smith",age:30,sex:'男'};//每一个都是一个新对象,属性值可以不固定
//person2 ={...};
printInfo(person);
}
/**
* 显示对象的属性方法二
*/
function myFunction2(){
person = new Object();
person.firstname ="David";
person.lastname = "Smith";
person.age = 30;
person.sex = '男';
printInfo(person);
}
/**
*构造函数
* @returns
*/
function Person(firstname,lastname,age,sex){
this.firstname = firstname;
this.lastname= lastname;
this.age = age;
this.sex = sex;
this.test = test2;//这个一定不能少
function test2(){
document.write("调用了Person的test()");
//alert("调用了Person的test()");
}
}
/**
* 显示对象的属性方法三
*/
function myFunction3(){
var p = new Person("David","Smith",30,'男');
//
p.test();
//
//printInfo(p);
}
/**
* 遍历Person对象的属性
*/
function traversalPerson(){
//这里如果要遍历的话,不能使用构造函数创建对象,
var p = {firstname:"David",lastname:"Smith",age:30,sex:'男'};
var str="";
var x;
for(x in p){
str += p[x]+",";//JS中用 "+=",php中用".="
}
//document.write(str);
document.getElementById("div1").innerHTML=str;
}
/********************通用的方法******************************/
/**
* 输出人物信息
*/
function printInfo(person){
document.getElementById("div1").innerHTML="姓名:" + person.firstname + " " + person.lastname + ",年龄:"+person.age+",性别:" + person.sex;
}
原文:http://blog.csdn.net/z18789231876/article/details/43764951