1.直接创建对象
var 对象变量名称 = new Object();
对象变量名称.属性名称 = 值;
对象变量名称.方法名称 = function(参数列表){
函数体
}
对象变量名称.属性名称;
对象变量名称.方法名称(参数);
//1.对象的创建
var person = new Object();//创建对象实例
//2.给对象添加属性
person.name = "张三";
person.age = 20;
//3.给对象添加方法
person.abc = function(){
alert("abc方法被调用");
}
//4.对象的方法及属性使用
console.log(person);
console.log(person.name);
console.log(person.age);
person.abc();
2.模板初始化创建对象
var 对象变量名称 = {
属性名称:值,
属性名称:值,
方法名称:function(参数列表){
函数体
}
//最后一个没有 逗号
}
var person = {
name : "张三",
age:20,
showName:function(name){
alert(this.name+name);
}
};
console.log(person);
console.log(person.name);
console.log(person.age);
person.showName("李四");
3.prototype原型方式对象创建
function 对象构造器(){
}
对象构造器.prototype.属性名 = 值;
对象构造器.prototype.方法名称 = function(参数列表){
函数体
}
function Person(){
}
Person.prototype.name="张三";
Person.prototype.age = 20;
Person.prototype.showName = function(){
alert(this.name);
}
//创建对象
var boy = new Person();
console.log(boy.age);
console.log(boy.name);
boy.showName();
构造器创建
function 对象构造器(参数列表){
this.属性名称 = 值;
this.方法名称 = function(参数列表){
函数体
};
this.方法名称1 = 方法名称2;
}
function 方法名称2(参数列表){
函数体
}
function Person(name,age){
this.name = name;
this.age = age;
this.showName = function(){
alert(this.name);
};
this.method = showAge;
}
function showAge(){
alert(this.age);
}
var boy = new Person("张三",20);
console.log(boy.name);
console.log(boy.age);
boy.showName();
boy.method();