//原型方式-->重點prototype(是Object擁有的一個屬性,因此所有的對象都擁有這個屬性)創立對象
//此種方式建立對象不能傳遞參數,因為該建構函式體內是個空的。
function Dog(){}
Dog.prototype.name = "小毛";//屬性值還可以是數組
Dog.prototype.age = 21;
Dog.prototype.get = function(name, age)
{
this.name = name;
this.age = age;
document.write("name:" + this.name + " , "+ "age:" + this.age );
}
//new Dog().get("野獸",24);
//另外一種用原型建立對象
function Cat(){}
Cat.prototype.name = new Array();
Cat.prototype.age = 3;
Cat.prototype.get = function()
{
document.write("name: " + this.name + " , " + "age:" + this.age,"<br/>");
}
var cat1 = new Cat();
cat1.name.push("張三");
cat1.name.push("李四");
cat1.age = 1;
cat1.get();
var cat2 = new Cat();
cat2.get();
//age是Number類型,是原型,它的值改變只是它的副本,並不會改變它本省。但是name是數群組類型的,它是參考型別,所以它的值會改變它本省。
//使用原型和建構函式的方法構建對象
//好處:即可共用原想對象中的方法,又可以通過構造方法建立對象的不通的屬性,一舉兩得。
function Person(name, age)
{
this.name = name;
this.age = age;
}
Person.prototype.get = function()
{
document.write("name:"+this.name+" , "+"age:"+this.age);
}
//new Person("曹歡",21).get();
//動態原型構造對象
//這種構造出來的對象的屬性值可以改變,但是方法卻只執行個體化一次(用flag標誌來確定)
function Dog(name, age)
{
//static sex = "男";
this.name = name;
this.age = age;
//alert(typeof Dog.asd == 'undefined');
if(typeof Dog.flag == "undefined")
{
alert("值執行了一次");
Dog.prototype.get = function()
{
document.write("name:"+this.name+" , age"+this.age);
}
Dog.flag = true;
//alert(Dog.flag);
}
}
var d1 = new Dog("小紫",21);
var d2 = new Dog("小花",22);
//d1.get();
//d2.get();