第一种:对象字面量的方式
var person = {
name: "小红",
age: 22,
say:function(){
console.log(this.name+"今年"+this.age);
}
};
person.say();
第二种:创建Object实例:
var obj = new Object();
obj.name = "肥狗";
obj.age = 23;
obj.say = function(){
console.log("我是"+this.name+"今年"+obj.age);
}
obj.say();
第三种:数构造函数
无参数构造函数
function Person(){
this.name = "孙悟空";
this.age = 18;
this.gender = "男";
this.sayName = function(){
console.log(this.name);
}
}
var per = new Person();
var per2 = new Person();
console.log(per);
console.log(per2);
带参数的构造函数
function Person(name,age,hobby){
this.name = name;
this.age = age;
this.hobby = hobby;
this.sayName = function(){
console.log(this.name);
}
}
var people = new Person("小妹",22,"跑步");
var people2 = new Person("小红",22,"跑步");
var people3 = new Person("小黄",22,"跑步");
console.log(people);
console.log(people2);
console.log(people3);
第四种:使用工厂方法创建对象
function creatPerson(name,age,tall){
//创建一个新的对象
var obj = new Object();
//向对象中添加属性
obj.name = name;
obj.age = age;
obj.tall = tall;
obj.sayName = function(){
console.log(this.name);
}
//将新的对象返回
return obj;
}
var obj2 = creatPerson("孙悟空",18,"1.55米");
var obj3 = creatPerson("猪八戒",35,"1.57米");
var obj4 = creatPerson("白骨精",25,"1.50米");
console.log(obj2);
console.log(obj3);
console.log(obj4);
第五种:原型方式创建对象
function Person(name,age){}
Person.prototype.name = "SF";
Person.prototype.age = 25;
Person.prototype.say = function() {
alert(this.name+"是我的名字");
}
var my = new Person();
my.say();
第六种:混合方式 (构造函数+原型)创建对象
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function() {
alert("我是"+this.name+",今年"+this.age);
}
var my = new Person("SF","25");
my.say();