toString() JavaScript 输出“保证”在每个浏览器/实现中都相同吗?

问题描述 投票:0回答:1

我正在使用一个特定的框架,并且在我的代码中的某个地方我有一个函数作为参数。

我想检查该函数是否是该框架之外的特定匿名函数。我无法访问原始函数本身来获得正确的参考。

我正在为自己创建一些调试工具(非生产),我想检查

func.toString()
的值是否为:

function(){return undefined }

...检查它是否是这个特定函数并处理一些特殊情况。

问题

JavaScript 输出是否“保证”在每个浏览器/实现中都相同?或者可能是其他浏览器将其格式化为不同的格式,删除不必要的空格或者根本不返回输出?

注意

我知道这些在任何正常情况下都是可怕的做法,但这将在只有我或我团队中的人会使用的调试工具中。理论上我们还可以控制我们使用的浏览器,但从理论的角度来看我更感兴趣。

代码

对于这个问题来说不是必需的,但可以提供更多背景信息。

代码是一个knockout.js调试绑定处理程序,我可以在其中轻松查看

toString()

是什么上下文。

element

用途:

ko.bindingHandlers.debug = { init: function(element:HTMLElement, valueAccessor:Action, allBindingsAccessor, viewModel, bindingContext:KnockoutBindingContext) { let value = valueAccessor(); // only "real way" to check for undefined, if the propery itself would be undefined // the normal use of valueAcessor() would also return undefined, so we can't differentiate between // an unexisting property or deliberately leaving out the property if ( valueAccessor.toString() == 'function(){return undefined }' ) value = bindingContext.$data; console.log( '----- Knockoutbinding -----' ); console.log( element ); console.log( value ); console.log( '---------------------------' ); } };


javascript knockout.js
1个回答
0
投票
<div data-bind="debug: window.innerHeight"> <!-- 450 --> <div data-bind="debug: window.nonExistingProperty"> <!-- undefined --> <div data-bind="debug: $data"></div> <!-- current context --> <div data-bind="debug"></div> <!-- current context (new) -->

函数是

规范
的一部分,但它不够严格,无法保证完整字符串比较(就像你所做的那样)能够工作。 规范强制执行的唯一事情是输出是有效的

Function.prototype.toString

,因此两个实现可以符合此规范,同时输出不同的缩进。

© www.soinside.com 2019 - 2024. All rights reserved.