• 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();		//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

  • 相关阅读:
    object-c iOS 教程 git for mac
    mac Git本地服务器配置
    [转]XCode中修改缺省公司名称/开发人员名称
    IOS------Warning
    Linux---CentOS 定时运行脚本配置练手
    微信公众号一些错误的原因错误代码41001
    微信支付的一些新的经验总结
    关于THINKPHP5模型关联的初步理解
    写下thinkphp5和thinkphp3.2的不同
    练手THINKPHP5过程和bootstrap3.3.7
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6771032.html
Copyright © 2020-2023  润新知