標籤:creat ret 寫作 http one highlight prot 方法 建構函式
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="jquery-1.9.1.js"></script><meta charset="utf-8" /></head><body> <button id="btn">提交</button></body><script>$(‘#btn‘).click(function(){ //通過object建立對象 var person =new Object(); person.name=‘wj‘; person.job=‘c#.net‘; person.fn=function(){ console.log(this.name+this.job); }; // person.fn(); //通過字面量建立對象 var conmpany={ name:"fanyaunwang", salary:"6500", fn:function(){ console.log(this.name+this.salary); } }; //conmpany.fn(); //以上2種方式建立對象,會產生大量的重複代碼 //通過原廠模式建立對象 // 原廠模式減少了代碼重複,但是不能識別對象,所有的執行個體都是object類型 function createObject(name,age,job) { var o = new Object(); o.name=name; o.age=age; o.job=job; o.fn=function(){ console.log(this.name+this.job+this.age); } return o; } //var wj=createObject(‘wj‘,‘22‘,‘c#.net‘); //wj.fn(); //通過建構函式建立對象 //建構函式中首字母大寫,而非建構函式首字母小寫作為區別 function CreatePerson(name,age,job) { this.name=name; this.age=age; this.job=job; this.fn=function(){ console.log(this.name+this.age+this.job); } } //通過new來建立CreatePerson執行個體,這樣建立的執行個體都有一個constractor //屬性指向CreatePerson //通過原廠模式建立的對象都是object,無法判讀對象的類型, //但是通過建構函式建立的對象可以,這是建構函式建立對象勝過 //通過原廠模式建立對象的地方 var obi=new CreatePerson(‘wangjun‘,‘23‘,‘c#.net‘); obi.fn(); console.log(obi.constructor==CreatePerson);//true //通過原型模式來建立對象 //原型模式就是在建構函式中吧方法拿出來的基礎上,在做了一層封裝 function Employee(){ } Employee.prototype.name=‘wangjun‘; Employee.prototype.age=‘c#‘; Employee.prototype.fn=function(){ console.log(this.name+this.age); } var emp=new Employee(); var emp1=new Employee(); emp.fn(); emp1.fn(); //這個fn是公用的 console.log(emp.fn()==emp1.fn());//true //在建構函式建立對象的模式中是false //建構函式和原型混合模式 //建立自訂類型的最常見方式 //建構函式模式用於定義執行個體屬性, //原型模式用於定義公用屬性 function Customer(name,address) { this.name=name; this.address=address; this.phone=[‘13946‘,‘44848484‘]; } Customer.prototype={ constructor:Customer, p:[‘af‘,‘sfasf‘], fnn:function(){ console.log(this.name+‘prototype‘); } } var objc= new Customer(‘fanyuanwang‘,‘shenzheng‘); var obje=new Customer(‘wangjin‘,‘changsha‘); console.log(objc.phone==obje.phone);//false //上面這個就是建構函式的參考型別的不同 objc.fnn(); console.log(objc.fnn==obje.fnn);//true objc.fnn();});</script>
Javascript建立對象的方法