天天看點

js建立對象的六種方式js建立對象的方式

js建立對象的六種方式

  • js建立對象的方式
    • object構造函數
    • 字面量建立對象
    • 工廠模式
    • 構造器建立對象
    • 構造器+原型建立對象
    • ES6通過類建立對象方式

js建立對象的方式

object構造函數

<script>
        var person = new Object;
        person.name = "wangcai";
        person.age = 100;
        person.say= function(){
            alert(this.name);
        }
    </script>
           

先建立一個Object對象,再為它添加屬性和方法。

字面量建立對象

<script>
        var person = {
            name : "wawngcai",
            age : 100,
            say : function(){
                alert(this.name);
            }
        }
    </script>
           

雖然object構造函數或對象字面量都可以用來建立單個對象,但這些方式有個明顯的缺點;使用同一個接口建立很多對象,會産生大量重複的代碼。

工廠模式

工廠模式:用函數來封裝以特定接口建立對象。

<script>
        function creatRect(width, height){
            var obj = {};
            obj.width = width;
            obj.height = height;
            obj.getC = function(){
                return width*2+height*2;
            }
            return obj;
        }
        var rect1 = creatRect(1,2);
        var rect2 = creatRect(3,4);
        var rect3 = creatRect(6,8);
        var rect4 = creatRect(10,10);
        console.log(rect3.getC());
    </script>
           

函數creatPerson()能根據接收的參數來建構一個包含所有必要資訊的Rect對象,可以無數次調用這個函數。

工廠模式雖然解決了建立多個相似對象的問題,但卻沒有解決對象識别的問題(即怎麼知道一個對象的類型)

構造器建立對象

構造函數模式:可用來建立特定類型的對象。

<script>
        function Person(name,age,job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.say = function(){
                alert(this.name)
            }
        }
        var person1 = new Person("wangcai",100,"Enlish");
        var person2 = new Person("xiaoqiang",50,"tearch");
        var person3 = new Person("wangcai",100,"Enlish");
    </script>
           

與工廠模式不同:

1)沒有顯示的建立對象

2)直接将屬性和方法賦給了this對象

3)沒有return語句

構造器+原型建立對象

好處:不必在構造函數中定義對象執行個體的資訊,而是可以将這些資訊直接添加到原型對象中。

<script>
        function Rect(){
            this.width = width;
            this.height = height;
        }
        Person.prototype.getS = function() { //将方法當成一個公有屬性
            retrun this.width * this.height;
        }
        var rect1 = new Rect(4,6);
    </script>
           

ES6通過類建立對象方式

<script>
        class Rect{
            constructor(width,height){
                this.width = width;  //私有屬性
                this.height = height;  //私有屬性
            }
            yy=110; //私有屬性
            getS(){ //公有屬性
                return this.width * this.height;
            }
             static xx = "123";//公有屬性
        }
        var rect1 = new Rect(2,4);
        console.log(rect1.hasOwnProperty("getS"));  //公有屬性
        console.log(rect1.getS()) //8
    </script>
           

大多數見到的都是用這種寫法。

繼續閱讀