1.object创建对象
var a = new Object();
a.name = "xiaoming";
a.age = 12;
a.sex = "男";
a.see = function (){
console.log(a.toString());
}
a.see();
2.工厂模式创建对象
function creatproduct(data){
var obj = new Object();
obj.name=data.name;
obj.price=data.price;
obj.color=data.color;
obj.grade=9.0;
return obj;
}
var xiaomi = {name:"mi6",price:"2800",color:"blue"};
var xiaominew = creatproduct(xiaomi);
for(var i in xiaominew){
console.log(xiaominew[i]);
}
3.基于构造函数创建对象
/*
* 把方法也写在构造函数中 每创建一个对象就拷贝一份到堆中 这样比较浪费内存
* */
function Product(data){
this.name = data.name;
this.price = data.price;
this.desc = data.desc;
this.buy = function(){
console.log();
}
}
var product = new Product({name:"aaa",price:"22",desc:"jidosjoasi"});
4.基于原型创建对象
/*在原型中 这样创建值类型的属性没问题因为在内存中 引用类型的属性在堆中就一分属于共享的所以导致每个对象的引用类型的属性值一样*/
function Product(){};
var product = new Product();
product.prototype.name="xiaomi";
product.prototype.price="111";
product.prototype.desc = {a:22,b:11}
product.prototype.buy=function(){
}
var product1 = new Product();
product1.prototype.name="xiaomi";
product1.prototype.price="111";
product1.prototype.desc = {a:22,b:11}
product1.prototype.buy=function(){
}
5.构造函数与原型混合创建对象
var Role =function() {
this.name = {nickName:'剑侠客',accountName:'876791562@qq.com'};
}
/*姓名*/
//生命值
Role.prototype.HP=100;
//魔法值
Role.prototype.MP=100;
//技能
Role.prototype.technologys=['普通攻击','横扫千军','地狱火','漫天飞雪'];
//跑起来
Role.prototype.run=function() {
alert('run');
}
/*引用类型有问题 -- 通过混合方式解决*/
var boy = new Role()
boy.name.nickName='剑侠客'
console.log(boy.name.nickName)
var girl = new Role()
girl.name.nickName = '可爱宝贝'
console.log(boy.name.nickName)
console.log(girl.name.nickName)
网友评论