下面小編就為大家?guī)?lái)一篇JS中多種方式創(chuàng)建對(duì)象詳解。小編覺(jué)得挺不錯(cuò)的?,F(xiàn)在分享給大家,給大家一個(gè)參考。
1.內(nèi)置對(duì)象創(chuàng)建
var girl=new Object();
girl.name='hxl';
console.log(typeof girl);
2.工廠模式,寄生構(gòu)造函數(shù)模式
function Person(name){
var p=new Object();//內(nèi)部進(jìn)行實(shí)例化
p.name=name;
p.say=function(){
console.log('my name is '+ p.name);
}
return p;//注:一定要返回
}
var girl=Person('haoxioli');
girl.say();
3.構(gòu)造函數(shù)創(chuàng)建
var Product=function(name){
this.name=name;
this.buy=function(){
console.log('我衣服的牌子是'+this.name);
}
}
var pro=new Product('真維斯');
pro.buy();
4.原型創(chuàng)建,缺點(diǎn):實(shí)例中的每個(gè)屬性有可能會(huì)不一樣
var Role=function(){}
Role.prototype.name={nickName:'昵稱'};
var boy=new Role();
boy.name.nickName='劉曉兵';
console.log(boy.name.nickName);//劉曉兵
var girl=new Role();
girl.name.nickName='郝曉利';
console.log(boy.name.nickName);//郝曉利,因?yàn)閷?shí)例對(duì)象可以修改原型中的引用對(duì)象的值
console.log(girl.name.nickName);//郝曉利
5.混合模式:原型+構(gòu)造,可以把不讓實(shí)例修改的屬性放到構(gòu)造函數(shù)中,可以修改的放原型中
var Role=function(){
this.name={nickName:'aaa'};
}
Role.prototype.age=30;
var boy=new Role();
boy.name.nickName='boy';
console.log(boy.name.nickName);//boy
var girl=new Role();
girl.name.nickName='girl';
console.log(boy.name.nickName);//boy,實(shí)例不會(huì)修改構(gòu)造函數(shù)中的值
console.log(girl.name.nickName);//girl
6.字面量形式
var cat={
name:'lucy',
age:3,
sex:'母'
};//將對(duì)象轉(zhuǎn)換成字符串
console.log(JSON.stringify(cat));//{"name":"lucy","age":3,"sex":"母"}
var dog='{"name":"john","sex":"公"}';
console.log(JSON.parse(dog).name);//將字符串轉(zhuǎn)為對(duì)象
7.拷貝模式
function extend(tar,source){
for(var i in source){
tar[i]=source[i];
}
return tar;
}
var boy={name:'醉俠客',age:20};
var person=extend({},boy);
console.log(person.name);
8.第三方框架
//先引入包
<script src='js/base2.js'></script>
//base2框架,Base.extend及constructor都是固定用法
var Animal=Base.extend({
constructor:function(name){
this.name=name;
},
say:function(meg){
console.log(this.name+":"+meg);
}
});
new Animal('lily').say('fish');
另一個(gè)第三方框架
<script src='js/simplejavascriptinheritance.js'></script>
//simplejavascriptinheritance框架,Class.extend及init都是固定用法
var Person=Class.extend({
init:function(name){
this.name=name;
}
});
var p=new Person();
p.name='over';
console.log(p.name);
以上這篇JS中多種方式創(chuàng)建對(duì)象詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考