在js中创建对象有3中方法,如果使用内置对象的方法创建对象也算的话就有四种。
- 使用json创建对象
var company={};
company.name='tx';
company.address='sz';
company.produce=function(msg){
alert(msg);
}
- 使用js中的Object类型创建对象
company=new Object();
company.name='tb';
company.address='hz';
company.produce=function(msg){
alert(msg);
}
- 使用构造函数创建对象
function Person(firstName,lastName,age){
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
var p = new Person(lisa,white,24);
而且对象是有类型的,要获取对象的类型,使用constructor
var arr=[2,1,3]
console.log(arr.constructor);//ƒ Array() { [native code] }
function Person(firstName,lastName,age){
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
var p = new Person('lisa','white',24);
console.log(p.constructor);
// ƒ Person(firstName,lastName,age){
// this.firstName=firstName;
// this.lastName=lastName;
// this.age=age;
//}
var oul=document.getElementById("ul");
console.log(oul.constructor);//ƒ HTMLUListElement() { [native code] }
- for-in语句
for-in语句是一种精准的迭代语句,可以用来枚举对象的属性,其语法:
for(property in window) statement
for(var propName in window){
document.write(propName+'<br/>'); }