js创建对象常用的几种方法
1.使用new关键字
var a = new Object();
2.通过字面量创建对象
var b = {
name:'张三';
}
3.工厂模式
function aa(name,age){
//1) 原材料
var bb = new Object()
bb.name = name;
bb.age = age
//2)加工
bb.create = function(){
console.log('我的名字是'+ bb.name+"年龄"+bb.age)
}
// 3)完工把对象返回出去
return bb
}
4.构造函数
构造函数和工厂模式区别
工厂模式里面要 new 一个对象 ,还需要return 这个对象
function bb(name,age){
this.name = name;
this.age = age;
this.create = function(){
console.log('我的名字是'+ this.name+"年龄"+this.age)
}
}
5.原型
function ooo(name){
ooo.prototype.name = name;
}
6.原型加构造函数(混合模式)
function bb(name,age){
this.name = name;
this.age = age;
this.create = function(){
console.log('我的名字是'+ this.name+"年龄"+this.age)
}
}
bb.prototype.run=function(){
console.log(this.name+"会跑")
}