0
点赞
收藏
分享

微信扫一扫

JavaScript灵活性


一提及JavaScript,大家都会想到其基于对象、简单、跨平台,然而其灵活性也值得大家津津乐道的!

一、数值调用方法



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

由于 Number 的实例就是数值,在数值上调用某个方法,数值会自动转为实例对象

2['add'](3);

(2).add(3);

等价于:


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

举报

相关推荐

0 条评论