以下是两个规则集,用于说明完全出乎意料的行为。这是一个错误吗?
即使没有在任何地方调用函数或者javascript错误导致脚本中断,函数也会执行。解决方案是始终使用分号结束声明:
test1 = function(){console.log("test1");} ;// <==
但我认为这很危险,因为这在javascript中不是强制性的。
示例1 bookmarklet :
javascript:(function(){
var d=document;var s=d.createElement('script');s.text="
KOBJ_config={'rids':['a1135x27']};";d.body.appendChild(s);
var l=d.createElement('script');l.src='http://init.kobj.net/js/shared/kobj-static.js';
d.body.appendChild(l);})()
示例2 bookmarklet :
javascript:(function(){
var d=document;var s=d.createElement('script');s.text="
KOBJ_config={'rids':['a1135x27']};";d.body.appendChild(s);
var l=d.createElement('script');l.src='http://init.kobj.net/js/shared/kobj-static.js';
d.body.appendChild(l);})()
规则集:
ruleset a1135x27 {
meta {
name "odd1"
description <<
demonstrate oddity 1
>>
author "Loïc Devaux"
logging on
}
dispatch {
// Some example dispatch domains
// domain "example.com"
// domain "other.example.com"
}
global {
emit <|
/* this breaks javascript code*/
// => 16:27:58 ERROR general Closure Executed with error a1135x27 - 13025536774875610960847698152Exception: test1 is not defined
test1 = function(){console.log("test1")}
/* this won't break */
//test1 = function(){console.log("test1")};
/* */
/* this won't break */
//test1 = function(){console.log("test1")}
//test2 = function(){console.log("test2")};
/* */
|>;
}
rule first_rule {
select when pageview ".*" setting ()
pre {
}
{
emit <|
test1();
|>;
}
}
}
ruleset a1135x28 {
meta {
name "odd2"
description <<
demonstrate oddity 2
>>
author "Loic Devaux"
logging on
}
dispatch {
// Some example dispatch domains
// domain "example.com"
// domain "other.example.com"
}
global {
emit <|
/* test1 will be executed even though it hasn't been called anywhere */
//test1 = function(){console.log("test1");}
/* */
/* test1 won't get executed */
/*
test1 = function(){console.log("test1");};
*/
/* */
/* this won't break and test2 will be executed although it hasn't been called anywhere */
test1 = function(){console.log("test1");}
test2 = function(){console.log("test2");}
/* */
|>;
}
rule first_rule {
select when pageview ".*" setting ()
pre {
}
{
emit <|
console.log('running first_rule');
|>;
}
}
}
答案 0 :(得分:2)
这里正确的做法是写有效的javascript。在您的代码示例中,您经常会留下重要的分号。请记住,虽然javascript相当容忍语法问题,但它们会以意想不到的方式让你陷入困境。
test2 = function(){console.log("test2")};
应该是
test2 = function(){console.log("test2");};
因为赋值都是一个语句,所以是console.log()
方法调用。
当您发出无效的javascript时,可能会发生各种奇怪的事情。虽然大多数会导致javascript语法错误,但KNS用于封装代码的封闭(并防止意外的变量泄漏)可能会产生您观察到的副作用。
简而言之:如果这里存在错误,那么javascript解析器可以灵活地省略重要的分号。这不被视为KRL错误。