原型模式說明
說明:使用原型實例來 拷貝 創建新的可定制的對象;新建的對象,不需要知道原對象創建的具體過程;
過程:Prototype => new ProtoExam => clone to new Object;
使用相關代碼:
Prototype.prototype.userInfo = function() {
return '個人信息, 姓名: '+this.name+', 年齡: '+this.age+', 性別:'+this.sex+'<br />';
}
現在需要兩個或以上的個人信息內容:
輸出返回:
原型模式,一般用于 抽象結構復雜,但內容組成差不多,抽象內容可定制,新創建只需在原創建對象上稍微修改即可達到需求的情況;
Object.create 使用說明
1>. 定義: 創建一個可指定原型對象的并可以包含可選自定義屬性的對象;
2> Object.create(proto [, properties]); 可選,用于配置新對象的屬性;
還可以包含 set, get 訪問器方法;
其中,[set, get] 與 value 和 writable 不能同時出現;
1. 創建原型對象類:
使用方法
1. 以 ProtoClass.prototype 創建一個對象;
2. 采用 實例化的 ProtoClass 做原型:
var obj2 = Object.create(proto, {
foo:{value:'obj2'}
});
obj2.aMethod(); //ProtoClass
obj2.foo; //obj2
3. 子類繼承:
SubClass.prototype.subMethod = function() {
return this.a || this.foo;
}
這種方法可以繼承 到 ProtoClass 的 aMethod 方法,執行;
要讓 SubClass 能讀取到 ProtoClass 的成員屬性,SubClass 要改下:
//其他代碼;
這種方法就可以獲取 ProtoClass 的成員屬性及原型方法;:
還有一種方法,就是使用 實例化的 ProtoClass 對象,做為 SubClass 的原型;
function SubClass() {
}
SubClass.prototype = Object.create(proto, {
foo:{value: 'subclass'}
});
這樣 SubClass 實例化后,就可以獲取到 ProtoClass 所有的屬性及原型方法,以及創建一個只讀數據屬性 foo;
4. 另外的創建繼承方法,跟 Object.create 使用 實例化的ProtoClass 做原型 效果一樣:
SubClass.prototype = new ProtoClass();
Object.create 相關說明
Object.create 用于創建一個新的對象,當為 Object 時 prototype 為 null, 作用與 new Object(); 或 {} 一致;
當為 function 時,作用與 new FunctionName 一樣;
//-----------------------------------------
function func() {
this.a = 'func';
}
func.prototype.method = function() {
return this.a;
}
var newfunc = new func();
//等同于[效果一樣]
var newfunc2 = Object.create(Object.prototype/*Function.prototype||function(){}*/, {
a: {value:'func', writable:true},
method: {value: function() {return this.a;} }
});
但是 newfunc 與 newfunc2 在創建它們的對象的函數引用是不一樣的.
newfunc 為 function func() {...},newfunc2 為 function Function { Native }
proto 為非 null, 即為已 實例化的值,即已經 new 過的值;javaScript 中的 對象大多有 constructor 屬性,這個屬性說明 此對象是通過哪個函數實例化后的對象;
propertiesField 為可選項,設定新創建對象可能需要的成員屬性或方法;
新聞熱點
疑難解答
圖片精選