创建对象主要有以下几种方式:对象字面量方式、构造函数模式、工厂模式、原型模式、混合模式
1)对象字面量方式
var person = {
age:10,
name:"小明",
eat:function(){
console.log("吃了一些东西");
}
}
2)构造函数模式
function Person(age,name){
this.age = age;
this.name = name;
this.eat = function(){
console.log("吃了一些东西");
}
}
3)工厂模式
function creatPerson(age,name){
var person = new Object();
person.age = age;
person.name = name;
person.eat = function(){
console.log("吃了一些东西");
}
return person;
}
4)原型模式
function Person(){}
Person.prototype.age = 10;
Person.prototype.name = "小明";
Person.prototype.eat = function(){
console.log("吃了一些东西");
}
5)混合模式
function Person(age,name){
this.age = age;
this.name = name;
}
Person.prototype.eat = function(){
console.log("吃了一些东西");
}
总结:
1、对象字面量:属性和方法都是key的形式
2、构造函数:属性和方法都是用this来指向
3、工厂模式:传入参数,要有返回值,跟构造函数的写法查不多
4、原型模式:通过prototype关键字来实现
5、混合模式:主要是构造函数模式加原型模式