您的位置:首页 > Web前端 > JavaScript

js几种创建对象方式及比较

2014-04-26 11:27 801 查看
<script>
//工厂模式 需要创建多个对象是出现问题
var oObj = new Object();
oObj.name = 'gogo';
oObj.price = 232323323;
oObj.run = function()
{
alert("能飞吗?");
}

//实现了创建了多个对象,通过构造方法,但是发现每个对象都对应一个版本的run方法,事实上应该都共享一个run方法
function Car(name,price)
{
var oTmpObj = new Object();
oTmpObj.name = name;
oTmpObj.price = price;
oTmpObj.run = function()
{
alert('能飞吗?');
}
return oTmpObj;
}

//重写上述方法,语义上感觉不是一个整体了
function run()
{
alert('能飞吗?');
}
function Car(name,price)
{
var oTmpObj = new Object();
oTmpObj.name = name;
oTmpObj.price = price;
oTmpObj.run = run;
return oTmpObj;
}

//构造函数方法创建,和上面一样出现每个对象对应一个版本的run方法
function Car(name,price)
{
this.name = name;
this.prive = price;
this.run = function()
{
alert("能飞吗?");
}
}

//原型链构造,属性限死了,出现多个对象公用一个属性现象
function Car(){}
Car.prototype.name = '兰博';
Car.prototype.price = 23232323;
Car.prototype.color = new Array('red','green','black')
car.prototype.run = function(){alert("能飞吗?")}
var oCar = new Car();

//混合方式,完美解决,唯一缺陷,看上去不是一个整体
function Car(name,price)
{
this.name = name;
this.price = price;
this.color = new Array('red','green','black');
}
Car.prototype.run = function(){alert('能飞吗?');}
var oCarObj = new Car();

//动态原型方式,更完美解决
function Car(name,price)
{
this.name = name;
this.price = price;
this.color = new Array('red','green','black');
//动态判定
if(typeof Car._initialed == 'undefined')
Car.prototype.run = function(){alert('能飞吗?')}
Car._initialed = true;
}

var oCarObj = new Car();
</script>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: