js原型prototype屬性用法執行個體

來源:互聯網
上載者:User

標籤:部分   沒有   封裝   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屬性用法執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.