JS是一门动态型语言:对象没有的属性,只要点了那么这个对象就有了这个属性,但是该属性没有赋值,输出就是undefined
一、创建对象四种方式
//1、字面量方式
var cat={
name:'花花',
age:2,
sex:'女',
eat:function(){
return '各种鱼类';
},
play:function(){
return '和主人玩';
}
};
document.write('小貓的名字是:'+cat.name+'<br/>');
document.write('小貓今年:'+cat['age']+'歲了<br/>');
document.write('小貓喜歡吃:'+cat.eat());
document.write('<hr/>');
//2、調用系統構造函數:
var dog=new Object();
dog.name='圓圓';
dog.age='3';
dog.sex='男';
dog.eat=function(){
return '骨頭';
};
dog.play=function(){
return '花花';
};
document.write('小狗的名字是:'+dog.name+'<br/>');
document.write('小狗今年:'+dog['age']+'歲了<br/>');
document.write('小狗喜歡吃:'+dog.eat());
document.write('<hr/>');
//3、自定義構造函數
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
this.play=function(){
return '花花和圓圓';
};
}
var zs=new Person('張三',12,'男');
document.write('小主人的名字是:'+zs.name+'<br/>');
document.write('小主人今年:'+zs['age']+'歲了<br/>');
document.write('小主人喜歡和:'+zs.play()+' 玩');
document.write('<br/>');
document.write(zs instanceof Person);
document.write('<hr/>');
//4、工廠方式創建對象
function creatObject(name,age){
var obj=new Object();
obj.name=name;
obj.age=age;
obj.country=function () {
return '中國';
}
return obj;
}
var ls=creatObject('李四','23')
document.write('大主人的名字是:'+ls.name+'<br/>');
document.write('大主人今年:'+ls['age']+'歲了<br/>');
document.write('大主人是:'+ls.country()+' 人');
document.write('<hr/>');
</script>
2、使用原型的例子
function changeColor(butId,divId,color){
this.butId=document.getElementById(butId);
this.divId=document.getElementById(divId);
this.color=color;
}
changeColor.prototype.init=function(){
var that=this;
this.butId.οnclick=function(){
that.divId.style.backgroundColor=that.color;
}
}
var Yellow=new changeColor('btn','box','yellow');
Yellow.init();
或者更高级写法:
function changeStyle(butId,divId,json){
this.butId=document.getElementById(butId);
this.divId=document.getElementById(divId);
this.json=json;
}
changeStyle.prototype.init=function(){
var that=this;
this.butId.οnclick=function(){
for (key in that.json) {
that.divId.style[key]=that.json[key];
}
}
}
var json1={
backgroundColor:'red',
height:'100px',
width:'100px'
}
var srr=new changeStyle('btn','box',json1);
srr.init();
3、构造函数、实例化对象、原型对象之间的关系