JS常用的幾種模式


先給你介紹下JS常用的幾種模式
1.原始模式
    //1.原始模式,對象字面量方式
var person = { 
    name: 'Jack',
    age: 18,
    sayName: function () { alert(this.name); }
};
//1.原始模式,Object構造函數方式
var person = new Object();
person.name = 'Jack';
person.age = 18;
person.sayName = function () {
    alert(this.name);
};
/*顯然,當我們要創建批量的person1、person2……時,
每次都要敲很多代碼,資深copypaster都吃不消!
然後就有了批量生產的工廠模式。*/
 
 
2.工廠模式
//2.工廠模式,定義一個函數創建對象
function creatPerson (name, age) {
    var person = new Object(); 
    person.name = name;
    person.age = age;
    person.sayName = function () {
        alert(this.name);
    };
    return person; 
}
/*
 工廠模式就是批量化生產,簡單調用就可以進入造人模式(啪啪啪……)。
 指定姓名年齡就可以造一堆小寶寶啦,解放雙手。
 但是由於是工廠暗箱操作的,所以你不能識別這個對象到底是什麼類型、
 是人還是狗傻傻分不清(instanceof 測試爲 Object),
 另外每次造人時都要創建一個獨立的temp對象,代碼臃腫,雅蠛蝶啊。
*/
3.構造函數
//3.構造函數模式,爲對象定義一個構造函數
function Person (name, age) {
    this.name = name;
    this.age = age;
    this.sayName = function () {
        alert(this.name);
    };    
}
var p1 = new Person('Jack', 18); //創建一個p1對象
Person('Jack', 18);   
 //屬性方法都給window對象,window.name='Jack',window.sayName()會輸出Jack
  
  
 4.原型模式
 //4.原型模式,直接定義prototype屬性
function Person () {}
Person.prototype.name = 'Jack';
Person.prototype.age = 18;
Person.prototype.sayName = function () { alert(this.name); };
//4.原型模式,字面量定義方式
function Person () {}
Person.prototype = {
    name: 'Jack',
    age: 18,
    sayName: function () { alert(this.name); }
};
var p1 = new Person(); //name='Jack'
var p2 = new Person(); //name='Jack'
 
//這裏需要注意的是原型屬性和方法的共享,即所有實例中
//都只是引用原型中的屬性方法,任何一個地方產生的改動會引起其他實例的變化。
 
5.混合模式(構造+原型)
//5. 原型構造組合模式,
function Person (name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype = {
    hobby: ['running','football'];
    sayName: function () { alert(this.name); },
    sayAge: function () { alert(this.age); }
};
var p1 = new Person('Jack', 20); 
//p1:'Jack',20; __proto__: ['running','football'],sayName,sayAge
var p2 = new Person('Mark', 18); 
//p1:'Mark',18;__proto__: ['running','football'],sayName,sayAge
 
 
//通過上面的例子,有什麼區別一目瞭然

原來地址:https://zhidao.baidu.com/question/1885625579728191988.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章