JavaScript靈活性,javascript

來源:互聯網
上載者:User

JavaScript靈活性,javascript
一提及JavaScript,大家都會想到其基於對象、簡單、跨平台,然而其靈活性也值得大家津津樂道的!
一、數值調用方法

Number.prototype.add = function(x){return this + x;};

由於 Number 的執行個體就是數值,在數值上調用某個方法,數值會自動轉為執行個體對象

2['add'](3); //5 調用方法之所以寫成8['add'],而不是8.add,是因為數值後面的點,會被解釋為小數點,而不是點運算子。

(2).add(3); //5

等價於:

2..add(3); //5第一個點解釋為小數點,第二個點解釋為點運算子。
Number.prototype.sub = function(x){return this - x;}

2['add'](3)['sub'](1);//4級聯調用

總之,現在我們可以在數值上直接調用方法了。

二、數值調用屬性
Number.prototype.double = function(){ return this + this; };Number.prototype.square = function(){ return this * this; };(2).double().square();//162['double']()['square']();//162..double().square();//16
但是,可以將上述兩個方法的調用改為讀取屬性的方式,ES5規定,每個對象的屬性都有一個取值方法get,用來自訂該屬性的讀取操作。
<pre name="code" class="javascript">Number.prototype = Object.defineProperty(Number.prototype,"double",{get:function(){return this + this;}});Number.prototype = Object.defineProperty(Number.prototype,"square",{get:function(){return this * this;}});(2).double.square;//162['double']['square'];//16


參考自:http://www.ruanyifeng.com/blog/2015/02/flexible-javascript.html

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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