Javascript 物件大小事
上班無聊,挖一些JS物件相關資訊紀錄:
var myobj = new object();
myboj.name = '小馬';
myobj.age = '28'
myobj.height = '181'
//可以改寫為
with(myboj){
name = '小馬';
age = '28';
height = '181';
}
//==========也可以使用建構函數==============
function SetProperty(name,age,height){
this.name = name;
this.age = age;
this.height = height;
}
var myobj = new SetProperty('小馬','28','181');
documnet.write(myobj.name) //小馬
//==========也可以將方法加入物件==============
function SetProperty(name,age,height){
this.name = name;
this.age = age;
this.height = height;
this.print = myfun;
}
function myfun(){
documnet.write(this.name + '<br>');
documnet.write(this.age + '<br>');
documnet.write(this.height + '<br>');
}
var myobj = new SetProperty('小馬','28','181');
myobj.print();
//小馬
//28
//181
//==========動態新增物件屬性、方法==============
function SetProperty(name,age,height){
this.name = name;
this.age = age;
this.height = height;
this.print = myfun;
}
function myfun(){
documnet.write(this.name + '<br>');
documnet.write(this.age + '<br>');
documnet.write(this.height + '<br>');
documnet.write(this.weight + '<br>');
}
function Caculate(){
document.write(1+1);
}
//替物件新增weight的屬性
SetProperty.prototype.weight = 72;
var myobj = new SetProperty('小馬','28','181');
myobj.print();
//小馬
//28
//181
//72
//替物件新增Caculate方法
SetProperty.prototype.execute = Caculate;
SetProperty.execute();
//2
//==========物件繼承==============
function SetProperty(name,age,height){
this.name = name;
this.age = age;
this.height = height;
}
function circle(r){
this.r = r;
this.showResult = showResult;
function showResult(){
var result = 3.14*r*r;
document.write(this.name + '<br>')
document.wirte('面積:' + result);
}
}
//Prototype物件繼承;
circle.prototype = new SetProperty('小馬');
var mycircle = new circle(2);
mycircle.showResult();
//小馬
//12.56