OO創建對象

工廠模式

<!DOCTYPE html>
<html>
<head>
    <title>Factory Pattern Example</title>
    <script type="text/javascript">

        function createPerson(name, age, job){
            var o = new Object();//創建
            //加工
            o.name = name;
            o.age = age;
            o.job = job;
            o.sayName = function(){
                alert(this.name);
            };    
            return o;
        }

        var person1 = createPerson("Nicholas", 29, "Software Engineer");
        var person2 = createPerson("Greg", 27, "Doctor");

        person1.sayName();   //"Nicholas"
        person2.sayName();   //"Greg"
    </script>
</head>
<body>

</body>
</html>

缺點:沒有解決對象識別的問題(即怎麼知道一個對象的類型)。


構造函數模式

像Object和Array這樣的原生構造函數,在運行時會自動出現在執行環境中。

<!DOCTYPE html>
<html>
<head>
    <title>Constructor Pattern Example</title>
    <script type="text/javascript">

        function Person(name, age, job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.sayName = function(){
                alert(this.name);
            };    
        }

        var person1 = new Person("Nicholas", 29, "Software Engineer");
        var person2 = new Person("Greg", 27, "Doctor");

        person1.sayName();   //"Nicholas"
        person2.sayName();   //"Greg"

        alert(person1 instanceof Object);  //true
        alert(person1 instanceof Person);  //true
        alert(person2 instanceof Object);  //true
        alert(person2 instanceof Person);  //true

        alert(person1.constructor == Person);  //true
        alert(person2.constructor == Person);  //true

        alert(person1.sayName == person2.sayName);  //false        


    </script>
</head>
<body>

</body>
</html>
  1. 沒有現實地創建函數
  2. 直接將屬性和方法賦給了this對象
  3. 沒有return語句
  4. 函數名開頭大寫,區別於其他函數,雖然也是函數,只不過可以用來創建對象而已。

要創建Person的新實例,必須使用new操作符。以這種方式調用構造函數實際上會經歷以下四個步驟:

  1. 創建一個新對象 var newObj=new object();
  2. 將構造函數的作用域賦給新對象(因此this就指向了這個新對象Person.apply.(newObj))
  3. 執行構造函數中的代碼(爲這個新對象添加屬性)
  4. 返回新對象
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章