JavaScript使用函数对象上的toString来读取文本内容 [英] JavaScript using toString on a Function object to read text content

查看:95
本文介绍了JavaScript使用函数对象上的toString来读取文本内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的函数中调用toString()可以跨浏览器返回不同的字符串。我理解这是因为ECMA-262 15.3.4.2为每个供应商留下了摆动空间。



除了所有语法,Chrome还会返回注释。可惜Firefox 3.6忽略了这些评论。基于Firefox的行为,我还没有测试IE,Opera或Safari。

  function foo(){
/ *评论* /
var bar = true;
}

具体来说,我试图将元数据嵌入特殊格式的注释块中一个函数。稍后,函数toString()方法的返回值将被解析并返回值作为对象。



我一直无法找到toString的兼容性表或替代方法( )。社区有什么想法吗?顺便说一句,预处理JS文件不是一个选项。 :(

非常感谢。)

试图最近回答这个问题,并且遇到了这个问题。为了提供更新,我仍然无法找到兼容性表格,所以我创建了以下小提琴:

https://jsfiddle.net/deamvp7r/

  if( function(){/ * test * /})。toString()。match('test')。length === 0){
alert(NO SUPPORT);
} else {
alert(SUPPORTED);
}

并在BrowserStack上手动测试。对于它的价值,下面是我测试过的浏览器以及我在Function.toString()中支持的评论:


  • IE8 - 11:支持评论

  • Firefox <= 16:无支持

  • Firefox> = 17: li>
  • Chrome 14 +:支持评论

  • IOS iPhone 3GS浏览器+:支持评论

  • iPad 1 +:支持评论

  • Android 2.3(Galaxy)+:支持评论



详尽,所以要小心,如果你不得不支持更老/更晦涩的浏览器呢。但支持评论的流行浏览器的比例目前似乎相当高。


Calling toString() on the function below returns different strings across browsers. I understand this is because ECMA-262 15.3.4.2 leaves wiggle room for each vendor.

Chrome returns the comments in addition to all syntax. Sadly Firefox 3.6 omits the comments. Based on Firefox's behavior I haven't tested IE, Opera, or Safari.

function foo() {
    /* comment */
    var bar = true;
}

Specifically, I am attempting to embed meta data within a specially formatted comment block within a function. Later the return value of the functions toString() method would be parsed and values returned as an object.

I've been unable to locate compatibility tables or alternatives to toString(). Does the community have any ideas? Btw, pre-processing JS files isn't an option. :(

Thanks a lot. :)

解决方案

I was trying to answer this question recently, and came across this. To provide an update, I was still unable to find a compatibility table, so I created the following fiddle:

https://jsfiddle.net/deamvp7r/

if((function(){ /*test*/ }).toString().match('test').length === 0) {
    alert ("NO SUPPORT");   
} else {
     alert ("SUPPORTED");   
}

and tested it manually on BrowserStack. For what it's worth, here are the browsers I've tested and what I've found so far as far as comment support in Function.toString():

  • IE8 - 11 : Supports comments
  • Firefox <= 16 : NO SUPPORT
  • Firefox >= 17 : Supports comments
  • Chrome 14 + : Supports comments
  • IOS iPhone 3GS browser + : Supports comments
  • iPad 1 + : Supports Comments
  • Android 2.3 (Galaxy) + : Supports Comments

This list is clearly far from exhaustive, so be careful if you have to support older/more obscure browsers yet. But the percentage of popular browsers that support comments currently seems pretty high.

这篇关于JavaScript使用函数对象上的toString来读取文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆