javascript 物件導向基礎 (1)

來源:互聯網
上載者:User

標籤:16px   面向   aaa   傳回值   不同   存在   size   建立對象   cti   

常見的建立對象的方式有3種:

① 聲明變數的方式

 

var obj1 = { key1: "val1", key1: "val2", show: function () { console.log(this.key1) } }var array = [1, 2, 3];

 

可以給 obj1 繼續添加屬性和方法,如:

obj1.color = "red";obj1.hideen = function () { console.log("aaa") };

 使用操作符 new

var obj2 = new Object();

可以給 obj2 繼續添加屬性和方法,如:

obj2.name = "madom";obj2.show = function () { console.log("aaa") };

③ 建立建構函式

function Cat() {             
  this.age = "18";  this.show = function () {    console.log(this.age);  }}

 

其實,建構函式 也是普通函數,只有當 new 操作的時候才是建構函式,

通過構 造函數 建立執行個體對象。每一個對象都有自己的內部原型 proto_

各個執行個體對象之間並不相同。

 

var cat1 = new Cat(); cat1.__proto__ === Cat.prototype; //truevar cat2 = new Cat(); cat2.__proto__ === Cat.prototype; //true cat1 === cat2; // fals  

再建立一個帶有 return 的建構函式

function Bird() {    this.age = 19;    this.say = function () { console.log(‘my age is ‘ + 19) };    return {        name: ‘Tim‘,        say: function () { console.log(‘hello ‘ + this.name) },    };}

建立一個對象執行個體,看看有什麼不同

var bird = new Bird();bird.say(); // hello Timconsole.log(bird); // Object {name: "Tim", say: function}

發現:如果建構函式有 return,則對象執行個體無法使用建構函式 return 之前的屬性和方法

 

new 操作時內部的運作大致如下:
第1步: 在記憶體中開闢一塊空間。
第2步: 建立一個新Null 物件,並把 this 指向到這個Null 物件。
第3步: 把Null 物件的 內部原型 指向 建構函式的 原型對象。
第4步: 當建構函式執行完成後,如果 沒有 return(傳回值) 的話,則建構函式末尾存在 ‘隱式’ 的 return this;如果  return(傳回值),則將傳回值賦值給對象執行個體。

對建立執行個體的操作做如下類比(非真實執行):

 

var cat1 = new Cat();/* this = { }; * this._proto_ = Cat.prototype * this = cat1; * return this */

 

 

 

--- 知識在於分享,轉載請注出處 ---

 

javascript 物件導向基礎 (1)

聯繫我們

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