zoukankan      html  css  js  c++  java
  • JavaScript(ES5)使用保留字作函数名

    ES5同意直接使用保留字作为属性名。但却不同意直接使用保留字作为函数名

    设现有类NSMap,若要给NSMap的原型加delete方法,如

    function NSMap(){
    
    }
    NSMap.prototype.delete=function delete(){
    
    };

    则浏览器解析报错

    SyntaxError: Unexpected token delete

    那么,为什么native code的Map能够办到?




    后来想到标识符能够由除ASCII特殊字符以外的大部分Unicode字符组成,方案来了:

    //1.从保留字中随便挑个字符出来,如字符t,算出字符t的十六进制charCode。

    "t".charCodeAt(0).toString(16)//"74"

    //2.尝试将t用x74表示。使用delex74e作为函数名,不行

    NSMap.prototype.delete=function delex74e(){
    	
    };
    

    //3.尝试将t用u0074表示,使用deleu0074e作为函数名,总算不报错了

    NSMap.prototype.delete=function deleu0074e(){
    	
    };
    

    //(这里有点不解。x74和u0074不是同一个意思吗,有可能是因解析器的性能考虑而不支持x)

    //4.假设函数是独立声明的,引用函数也不得直接使用字面保留字

    function deleu0074e(){
    	
    }
    NSMap.prototype.delete=deleu0074e;
    

    //用得较多时,能够參照Chrome底层JavaScript源代码那样写

    InstallFunctions(NSMap.prototype,DONT_ENUM,[
    	"extends",function exu0074ends(){
    		
    	},
    	"delete",function deleu0074e(){
    		
    	}
    ]);




    另附上一个转义函数

    function toCharCodeString(){
    	return Array.prototype.map.call(new String(this),function(c){
    		var code=c.charCodeAt(0),
    			hex=code.toString(16);
    		//return code>0xff?

    // "\u"+"000".substr(0,4-hex.length)+hex: // "\x"+"0".substr(0,2-hex.length)+hex; return "\u"+"000".substr(0,4-hex.length)+hex; }).join(""); } toCharCodeString.call("delete"); // "u0064u0065u006cu0065u0074u0065" toCharCodeString.call("Unicode字符"); // "u0055u006eu0069u0063u006fu0064u0065u5b57u7b26"




  • 相关阅读:
    分布式事务总结
    正确使用HttpClient,避免出现大量CLOSE_WAIT的TCP链接
    年终总结
    不如自己读一遍AsyncTask源码
    Android支持的图片格式
    Java Annotation Tutorials
    Android中的LruCache
    Hadoop DistributedCache分布式缓存的使用
    Mapreduce设置多路径输入输出
    Ubuntu Server 12.04安装CDH5方法总结
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5409231.html
Copyright © 2011-2022 走看看