js--使用構造器函數來建立對象及操作

來源:互聯網
上載者:User

標籤:

通過new操作符來調用函數,來達到訪問對象this值得目的,構造器將其建立的對象返回給我們。

直接上代碼

 

//建立構造器函數

function Gadget(name, color){

  this.name = name ;//添加屬性

  this.color = color ;

  this.whatAreYou = function(){//添加方法

    return this.color + " " + this.name ;

  }

}

//另一種添加屬性和方法,通過構造器函數的prototype屬性來添加

Gadget.prototype.price = 100;//原型屬性

Gadget.prototype.rating = 3;

Gadget.prototype.getInfo = function(){

  return this.price+" "+this.rating;

}

 

/*簡寫

Gadget.prototype = {

  price:100,

  rating = 3,

  getInfo = function(){

    return this.price + " "+this.rating;

  }

}

*/

 

//使用構造器來建立對象

var newtoy = new Gadget(‘webcam‘,‘black‘);

newtoy.name;//

---->>webcam

 

 

//對象傳遞的方式是通過傳引用,即所建立的對象實體中並沒有儲存一份屬於自己的原型副本,值傳遞會產生副本

Gadget.prototype.get = function(what){

  return this[what];

}

 

//newtoy.name

如果對象自身的屬性和原型中同上存在name屬性,對象自身的屬性優先順序高於原型的屬性

當刪除(delete newtoy.name)對象屬性時,原型中的name屬性就被使用

js--使用構造器函數來建立對象及操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.