javascript如何建立對象_javascript技巧

來源:互聯網
上載者:User

JS是基於對象的語言,可以使用物件導向思想類比JAVA|C++之類的物件導向語言。
 •面向過程
◦關註解決問題的步驟

 •物件導向
◦關注的是解決問題的所需要的對象(內容和角色),然後根據商務邏輯按一定規則調用相關方法

對象分為系統對象和自訂對象兩種。我們可以通過調用系統建構函式來建立出系統對象,如:array|date等。自訂對象必須自己創造,無法利用系統函數來創造。

javascript建立對象 

一、直接建立

 //直接建立     //JS建立對象     //1:建立Null 物件         var person1 = new Object();     //2:將該對象所需要的屬性、方法加進去         person1.name ="ailer" ;         console .log(person1.name);         person1.gender = "male";     //3:該對象添加的方法|(函數)         person1. manager= function (){           console .log("Ailer is my English name" );        }     //4:調用對象方法:對象.方法名();         person1.manager();     //函數|方法?函數屬於對象時,該函數屬於這個對象下的方法;通過方法名來調用該函數;     //變數|屬性 ?當變數屬於某一個對象時候, 該變數就是這個對象下的方法。通過屬性名稱來調用變數。      //增         person1.age ="6" ;      //改         person1.name ="lemon" ;      //查         console .log(person1.name);     //刪         delete person1.age;         console .log(person1.age);==> undefined      //參考型別,儲存的是地址      //基本類型:儲存的是值 標誌位     /*  var arr1 = [1,2,3,4]        var arr2 = [5, 6, 7,9];        var arr2 = arr1;//        arr2[0]=10;//更改arr2裡面的值,arr1也更改        alert(arr1[0]);//====>10 參考型別*/        var per2 = new Object();        per2.name = "Relia";        per2.age = "18";        per2.gender = "femal";        per2.hobby = "lemons";         //1:通過.(點文法)訪問屬性         //2:通過[](方括弧)訪問對象的屬性;方括弧中必須是屬性字串或儲存屬性字串的變數|遍曆屬性的時候才使用方括弧         var n = "name"         //console.log(per2["name"]);//雙引號         console .log(per2[n]);         for ( var property in per2) {//          console.log(per2[property]);         }

雖然直觀,但是建立多個對象的時候,代碼冗餘

二、使用函數建立(原廠模式)

為瞭解決多個類似對象聲明的問題,我們可以使用一種叫做原廠模式的方法,這種方法就是為瞭解決執行個體化對象產生大量重複的問題。

//定義建構函式       function createPerson ( name, age) {//建立一個新的Null 物件           var person = new Object;//添加屬性|方法           person.name = name;           person.age = age;           person. manager = function() {              console .log("ai" );           }//返回           return person;        }         var per1 = createPerson( "ailer", 12 );         console .log(per1.name);        var per2 = createPerson( "lemon", 23 );        console .log(per2.age);        console.log(per2 instanceof Object);//true        console.log(per2 instanceof createPerson);//false//無法區分該物件類型        console.log(per2.manager==per1.manager);//false 可得出per1和per2各自開閉空間

優:大量建立同類執行個體
缺:執行個體用同類屬性, 造成記憶體浪費無法公,且無法區分該對象的類型

三、 字面量建立

優:簡單直接
缺:無法批量構建同類對象

//字面量建立的對象使用constructor屬性不會指向執行個體,而是指向object //使用字面量建立       var per1 = {        name:"Ailer",         constructor:per1,        age:12,        gender:"female",        hobby:"play",        eat:function(){          console.log(this.name);        }       }       per1.eat();//ailer       per1.name="lemon";       per1.eat();//lemon       console.log(typeof per1);//Object       console.log(per1.constructor==Object);//true

 四、new+建構函式

//建構函式建立對象,其子物件用instanceof不識別,所有採用new+obj建立        //對象識別了,但是仍然浪費一些代碼區;==>產生原型建立        //建立js對象 new+建構函式        //1:建立建構函式 |通常首字母大寫        function CreatePerson( name , age){          //2:把對象的屬性|方法掛靠在this指標身上, 當調用該函數建立對象時,this指標就指向這個新對象;          //這個this就添加給這個對象          this.name = name;          this.age = age;          /*this.speak = function(){            //此處this也指向建立對象            console.log(this.name+" hello");          }        }      /* CreatePerson.prototype.gender = "20";       CreatePerson.prototype. ea = function(){          console .log(this.name+ "sfd" );       }*///      __proto__:是:執行個體對象中的原型屬性, 指向對應建構函式對應的原型對象//      [[prototype]]        //調用        var per1 = new CreatePerson( "ailer", "20" );        var per2 = new CreatePerson( "relia", "18" );        console .log(per1 instanceof CreatePerson); //==true        console .log(per2 instanceof CreatePerson); //==>true        console .log(per1.speak== per2.speak); //==false說明系統開闢了兩個不同的代碼區,造成了記憶體浪費.

字面量建立一個比較方便,所以產生建構函式,普通建構函式(原廠模式),子物件instanceof不識別且記憶體浪費,用new+建構函式,子物件識別了,但仍有部分代碼重複,記憶體浪費,產生原型代碼解決。

五、原型模式

      function CreateAnimal(name, age) {        //1.2:把外部參數綁定執行個體屬性        this.name = name;        this.age = age;      }      //1.3把相同的屬性,綁定在原型上(原型屬性,原型方法)      CreateAnimal.prototype.gender = "male";      CreateAnimal.prototype.style = function() {        console.log(this.name + " ailers");      };      //2:調用建構函式建立對象      var cat1 = new CreateAnimal("xiaohua", "2");      var cat2 = new CreateAnimal("xiaohua", "2");      cat1.style();      console.log(cat1.style==cat2.style);//方法引用地址一樣,將屬性放到原型對象中,節約地址      //instanceof可以來判斷對象屬於哪一個【函數】      //constructor 建造者 也可以用來判斷對象屬於哪個【建構函式】 【常】       //執行個體對象儲存一個 constructor屬性指向它的建構函式      //instanceof and constructor 區別      console.log(cat1 instanceof CreateAnimal);//true      console.log(cat1 instanceof Object);//true      console.log(cat1.constructor == CreateAnimal);//true      console.log(cat1.constructor == Object); //==false      //建構函式的原型也有constructor屬性指會建構函式      console.log(CreateAnimal.prototype.constructor == CreateAnimal);//true      //in判斷該屬性是否存在這個對象中,這個屬性為執行個體屬性或原型 //           alert("name" in cat1)//true//           alert("gender" in cat1);//true      //hasOwnProperty:來判斷某一個屬性到底是執行個體屬性,還是繼承自原型屬性 if 是 為true, else不存在|不是返回false;      console.log(cat1.hasOwnProperty("aaa"));//false 不存在的屬性返回為false      console.log(cat1.hasOwnProperty("name"));//true 執行個體屬性      console.log(cat1.hasOwnProperty("style"));//false 原型屬性返回為false      //遍曆屬性找原型屬性      //判斷參數是否為原型屬性  工具類      console.log(isPrototype("gender", cat1));//true      function isPrototype(proString, obj) {        if(proString in obj) {          if(!obj.hasOwnProperty(proString)) {            return true;          } else {            return false;          }        } else {          return false;        }      }      /*function isProperty(object, property) {//判斷原型中是否存在屬性   return !object.hasOwnProperty(property) && (property in object);}*/

動態原型模式

//建構函式中初始化原型function per(name, age, gender) {        this.name = name;        this.age = age;        this.gender = gender;        //只在初始化原型的時候執行一次        if(typeof this.sayName != "function") {          Person.prototype.sayName = function() {            alert(this.name);          }        }      }

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.