標籤:部分 沒有 封裝 bst js原型 優先 建構函式 模式 document
//原型方法建立對象的屬性和方法,達到共用的目的function Box(){};//裡面什麼都沒有,如果有就是執行個體屬性和方法Box.prototype.name=‘tianwei‘;Box.prototype.age=‘100‘;Box.prototype.run=function(){ return this.name+this.age;};var box1=new Box();document.write(box1.name);
執行個體屬性不會共用,原型屬性共用,優先訪問執行個體屬性
//刪除屬性:delete box1.name;delete Box.prototype.name;//判斷屬性是否在執行個體裡面:box1.hasOwnProperty(‘name‘); //只要有這個屬性就返回true‘name‘ in box1;
//原型方法建立對象的屬性和方法,達到共用的目的function Box(){};//裡面什麼都沒有,如果有就是執行個體屬性和方法Box.prototype={ constructor:Box, name:‘tianwei‘, age:‘100‘, run:function(){ return this.name+this.age; }}var box1=new Box();document.write(box1.constructor);
var box= [1,2,3,2,10,3];document.write(box.sort());/*Array.prototype.sort;*/alert(String.prototype.substr);String.prototype.addString=function(){ return this+‘添加成功‘;};var box=‘4343‘;alert(box.addString());
需要獨立部分使用建構函式
需要共用部分使用原型模式
//組合構造函數+原型function Box(name,age){ //需要獨立部分 this.name=name; this.age=age; this.family=[‘1‘,‘2‘,‘3‘];}Box.prototype={ //共用部分 constructor:Box, run:function(){ return this.name+this.age; }}var box1=new Box(‘tian‘,100);box1.family.push(‘4‘);alert(box1.family);var box2=new Box(‘wei‘,200);alert(box2.family);
把上面封裝在一起,使用
動態原型模式
//組合構造函數+原型function Box(name, age) { //需要獨立部分 this.name = name; this.age = age; this.family = [‘1‘, ‘2‘, ‘3‘]; //原型只需要初始化一次 if (typeof this.run != ‘function‘) { Box.prototype.run = function() { return this.name + this.age; } }}var box1 = new Box(‘aaa‘, 111);alert(box1.run());var box2 = new Box(‘bbb‘, 222);alert(box2.run());
js原型prototype屬性用法執行個體