一提及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(); //16
2['double']()['square'](); //16
2..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; //16
2['double']['square']; //16



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